# 升級指南
*****
If you are upgrading from version 3 to version 4, these are the significant changes that you need to be aware of.
> 如果您正在從版本3升級到版本4,那么您需要注意以下重要更改。
## PHP 版本要求
Slim 4 requires**PHP 7.1 or newer**.
## 更改為Slim\App構造函數
Slim’s App settings used to be a part of the container and they have now been decoupled from it.
> Slim的應用程序設置曾經是容器的一部分,現在它們已與容器解耦。
~~~php
/**
* Slim 3 App::__construct($container = [])
* As seen here the settings used to be nested
*/
$app = new App([
'settings' => [...],
]);
/**
* Slim 4 App::__constructor() method takes 1 mandatory parameter and 4 optional parameters
*
* @param ResponseFactoryInterface Any implementation of a ResponseFactory
* @param ContainerInterface|null Any implementation of a Container
* @param CallableResolverInterface|null Any implementation of a CallableResolver
* @param RouteCollectorInterface|null Any implementation of a RouteCollector
* @param RouteResolverInterface|null Any implementation of a RouteResolver
*/
$app = new App(...);
~~~
## 刪除應用程序設置
* `addContentLengthHeader`See[Content Length Middleware](http://www.slimframework.com/docs/v4/middleware/content-length.html)for new implementation of this setting.
* `determineRouteBeforeAppMiddleware`Position[Routing Middleware](http://www.slimframework.com/docs/v4/middleware/routing.html)at the right position in your middleware stack to replicate existing behavior.
* `outputBuffering`See[Output Buffering Middleware](http://www.slimframework.com/docs/v4/middleware/output-buffering.html)for new implementation of this setting.
* `displayErrorDetails`See[Error Handling Middleware](http://www.slimframework.com/docs/v4/middleware/error-handling.html)for new implementation of this setting.
> * `addContentLengthHeader`有關此設置的新實現,請參閱[內容長度中間件](http://www.slimframework.com/docs/v4/middleware/content-length.html)。
> * `determineRouteBeforeAppMiddleware`將[路由中間件](http://www.slimframework.com/docs/v4/middleware/routing.html)放置在中間件堆棧中的正確位置,以復制現有行為。
> * `outputBuffering`有關此設置的新實現,請參見[輸出緩沖中間件](http://www.slimframework.com/docs/v4/middleware/output-buffering.html)。
> * `displayErrorDetails`有關此設置的新實現,請參見[錯誤處理中間件](http://www.slimframework.com/docs/v4/middleware/error-handling.html)。
## 改變容器
Slim no longer has a Container so you need to supply your own. If you were relying on request or response being in the container, then you need to either set them to a container yourself, or refactor. Also,`App::__call()`method has been removed, so accessing a container property via`$app->key_name()`no longer works.
> Slim不再有容器,所以您需要提供自己的容器。如果您依賴于請求或響應在容器中,那么您需要自己將它們設置為容器,或者進行重構。此外,`App:: call() `方法已被刪除,因此通過`$ App ->key_name()`訪問容器屬性不再工作。
## 對路由組件的更改
The`Router`component from Slim 3 has been split into multiple different components in order to decouple FastRoute from the`App`core and offer more flexibility to the end user. It has been split into`RouteCollector`,`RouteParser`and`RouteResolver`. Those 3 components can all have their respective interfaces which you can implement on your own and inject into the`App`constructor. The following pull requests offer a lot of insight on the public interfaces of these new components:
> 來自Slim 3的“Router”組件被分成多個不同的組件,以將FastRoute從“App”核心中分離出來,并為終端用戶提供更多的靈活性。它被分為“RouteCollector”、“RouteParser”和“RouteResolver”。這三個組件都有各自的接口,你可以自己實現并注入到“App”構造函數中。下面的拉請求提供了關于這些新組件的公共接口的大量信息:
* [Pull Request #2604](https://github.com/slimphp/Slim/pull/2604)
* [Pull Request #2622](https://github.com/slimphp/Slim/pull/2622)
* [Pull Request #2639](https://github.com/slimphp/Slim/pull/2639)
* [Pull Request #2640](https://github.com/slimphp/Slim/pull/2640)
* [Pull Request #2641](https://github.com/slimphp/Slim/pull/2641)
* [Pull Request #2642](https://github.com/slimphp/Slim/pull/2642)
## 新的中間件的方法
In Slim 4 we wanted to give more flexibility to the developers by decoupling some of Slim’s App core functionality and implementing it as middleware. This gives you the ability to swap in custom implementations of the core components.
> 在Slim 4中,我們希望通過解耦Slim的一些核心功能并將其作為中間件實現,從而為開發人員提供更大的靈活性。這使您能夠交換核心組件的自定義實現。
## 執行中間件
Middleware execution has not changed and is still`Last In First Out (LIFO)`like in Slim 3.
> 中間件執行沒有改變,仍然是`Last In First Out (LIFO)`,就像在Slim 3中一樣。
## 新的應用工廠
The`AppFactory`component was introduced to reduce some of the friction caused by decoupling the PSR-7 implementation from the`App`core. It detects which PSR-7 implementation and ServerRequest creator is installed in your project root and enables you to instantiate an app via`AppFactory::create()`and use`App::run()`without having to pass in a`ServerRequest`object. The following PSR-7 implementations and ServerRequest creator combos are supported:
> 引入`AppFactory`組件是為了減少將PSR-7實現與`App`內核解耦所帶來的一些摩擦。它可以檢測在您的項目根目錄中安裝了哪些PSR-7實現和ServerRequest creator,并允許您通過`AppFactory::create()`實例化一個應用程序,并使用`app::run()`,而不必傳遞一個`ServerRequest`對象。支持以下PSR-7實現和ServerRequest creator組合:
* [Slim PSR-7](https://github.com/slimphp/Slim-Psr7)
* [Nyholm PSR-7](https://github.com/Nyholm/psr7)and[Nyholm PSR-7 Server](https://github.com/Nyholm/psr7-server)
* [Guzzle PSR-7](https://github.com/guzzle/psr7)and[Guzzle HTTP Factory](https://github.com/http-interop/http-factory-guzzle)
* [Zend Diactoros](https://github.com/zendframework/zend-diactoros)
## 新的路由中間件
The routing has been implemented as middleware. We are still using[FastRoute](https://github.com/nikic/FastRoute)for our routing needs. If you were using`determineRouteBeforeAppMiddleware`, you need to add the`Middleware\RoutingMiddleware`middleware to your application just before you call`run()`to maintain the previous behaviour. See[Pull Request #2288](https://github.com/slimphp/Slim/pull/2288)for more information.
> 路由已作為中間件實現。我們仍然使用[FastRoute](https://github.com/nikic/FastRoute)來滿足我們的路由需求。如果您正在使用`determineroutebeforeappmiddleware`,那么您需要在調用`run()`之前將'中間件\路由中間件'中間件添加到您的應用程序中,以維護前面的行為。有關更多信息,請參見[Pull Request #2288](https://github.com/slimphp/Slim/pull/2288)。
~~~php
<?php
use Slim\Factory\AppFactory;
require __DIR__ . '/../vendor/autoload.php';
$app = AppFactory::create();
// Add Routing Middleware
$app->addRoutingMiddleware();
// ...
$app->run();
~~~
## 新的錯誤處理中間件
Error handling has also been implemented as middleware. See[Pull Request #2398](https://github.com/slimphp/Slim/pull/2398)for more information.
> 錯誤處理也作為中間件實現。有關更多信息,請參見[Pull Request #2398](https://github.com/slimphp/Slim/pull/2398)。
~~~php
<?php
use Slim\Factory\AppFactory;
require __DIR__ . '/../vendor/autoload.php';
$app = AppFactory::create();
/*
* The routing middleware should be added before the ErrorMiddleware
* Otherwise exceptions thrown from it will not be handled
*/
$app->addRoutingMiddleware();
/*
* Add Error Handling Middleware
*
* @param bool $displayErrorDetails -> Should be set to false in production
* @param bool $logErrors -> Parameter is passed to the default ErrorHandler
* @param bool $logErrorDetails -> Display error details in error log
* which can be replaced by a callable of your choice.
* Note: This middleware should be added last. It will not handle any exceptions/errors
* for middleware added after it.
*/
$app->addErrorMiddleware(true, true, true);
// ...
$app->run();
~~~
## 新的調度程序和路由結果
We created a wrapper around the FastRoute dispatcher which adds a result wrapper and access to a route’s full list of allowed methods instead of only having access to those when an exception arises. The Request attribute`routeInfo`is now deprecated and replaced with`routingResults`. See[Pull Request #2405](https://github.com/slimphp/Slim/pull/2405)for more information.
> 我們圍繞FastRoute dispatcher創建了一個包裝器,它添加了一個結果包裝器,并訪問一個路由的允許方法的完整列表,而不是只在異常發生時訪問這些方法。請求屬性`routeInfo`現在被棄用,代之以`routingResults`。有關更多信息,請參見[Pull Request #2405](https://github.com/slimphp/Slim/pull/2405)。
~~~php
<?php
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;
use Slim\Routing\RouteContext;
require __DIR__ . '/../vendor/autoload.php';
$app = AppFactory::create();
$app->get('/hello/{name}', function (Request $request, Response $response) {
$routeContext = RouteContext::fromRequest($request);
$routingResults = $routeContext->getRoutingResults();
// Get all of the route's parsed arguments e.g. ['name' => 'John']
$routeArguments = $routingResults->getRouteArguments();
// A route's allowed methods are available at all times now and not only when an error arises like in Slim 3
$allowedMethods = $routingResults->getAllowedMethods();
return $response;
});
// ...
$app->run();
~~~
## 新方法覆蓋中間件
If you were overriding the HTTP method using either the custom header or the body param, you need to add the`Middleware\MethodOverrideMiddleware`middleware to be able to override the method like before. See[Pull Request #2329](https://github.com/slimphp/Slim/pull/2329)for more information.
> 如果您正在使用自定義頭或主體參數覆蓋HTTP方法,則需要添加“Middleware\MethodOverrideMiddleware”中間件,以便能夠像以前那樣覆蓋該方法。有關更多信息,請參見[Pull Request #2329](https://github.com/slimphp/Slim/pull/2329)。
~~~php
<?php
use Slim\Factory\AppFactory;
use Slim\Middleware\MethodOverridingMiddleware;
require __DIR__ . '/../vendor/autoload.php';
$app = AppFactory::create();
$methodOverridingMiddleware = new MethodOverridingMiddleware();
$app->add($methodOverridingMiddleware);
// ...
$app->run();
~~~
## 新內容長度中間件
The Content Length Middleware will automatically append a`Content-Length`header to the response. This is to replace the`addContentLengthHeader`setting that was removed from Slim 3. This middleware should be placed on the center of the middleware stack so it gets executed last.
> 內容長度中間件將自動向響應附加一個“Content-Length”標頭。這是為了取代“addContentLengthHeader”設置從Slim 3刪除。這個中間件應該放在中間件堆棧的中心,這樣它才會最后執行。
~~~php
<?php
use Slim\Factory\AppFactory;
use Slim\Middleware\ContentLengthMiddleware;
require __DIR__ . '/../vendor/autoload.php';
$app = AppFactory::create();
$contentLengthMiddleware = new ContentLengthMiddleware();
$app->add($contentLengthMiddleware);
// ...
$app->run();
~~~
## 新的輸出緩沖中間件
The Output Buffering Middleware enables you to switch between two modes of output buffering:`APPEND`(default) and`PREPEND`mode. The`APPEND`mode will use the existing response body to append the content while`PREPEND`mode will create a new response body and append it to the existing response. This middleware should be placed on the center of the middleware stack so it gets executed last.
> 輸出緩沖中間件允許您在兩種輸出緩沖模式之間進行切換:`APPEND `(默認)和`PREPEND`模式。`APPEND`模式將使用現有的響應體來附加內容,而`PREPEND`模式將創建一個新的響應體并將其附加到現有響應中。這個中間件應該放在中間件堆棧的中心,這樣它才會最后執行。
~~~php
<?php
use Slim\Factory\AppFactory;
use Slim\Middleware\OutputBufferingMiddleware;
require __DIR__ . '/../vendor/autoload.php';
$app = AppFactory::create();
/**
* The two modes available are
* OutputBufferingMiddleware::APPEND (default mode) - Appends to existing response body
* OutputBufferingMiddleware::PREPEND - Creates entirely new response body
*/
$mode = OutputBufferingMiddleware::APPEND;
$outputBufferingMiddleware = new OutputBufferingMiddleware($mode);
// ...
$app->run();
~~~
- 開始
- 安裝
- 升級指南
- Web服務器
- 概念
- 生命周期
- PSR 7
- 中間件
- 依賴容器
- 實例 及通知和警告處理
- Request
- 請求方法
- 請求頭信息
- 請求主體
- 上傳的文件
- 請求幫助
- 路由對象
- Response
- 響應狀態
- 響應標頭
- 響應體
- 返回JSON
- 視圖模板
- 路由
- 創建路由
- 路由回調
- 路由策略
- 路線占位符
- 路由名
- 路由組
- 路由中間件
- 路由表達式緩存
- 容器識別解析
- 封裝中間件
- 路由的中間件
- 錯誤處理中間件
- 方法重寫的中間件
- 輸出緩沖中間件
- 內容長度中間件
- 擴展功能
- 以 / 結尾的路由模式
- 獲取當前路由
- 設置CORS
- 使用POST表單上傳文件
- 第三方組件
- slim-session
- auth
- slim-api-skeleton
- dir