Upgrade Guide

If you are upgrading from version 3 to version 4, these are the significant changes thatyou need to be aware of.

PHP Version Requirement

Slim 4 requires PHP 7.1 or newer.

Breaking changes to Slim\App constructor

Slim’s App settings used to be a part of the container and they have now been decoupled from it.

  1. /**
  2. * Slim 3 App::__construct($container = [])
  3. * As seen here the settings used to be nested
  4. */
  5. $app = new App([
  6. 'settings' => [...],
  7. ]);
  8. /**
  9. * Slim 4 App::__constructor() method takes 1 mandatory parameter and 4 optional parameters
  10. *
  11. * @param ResponseFactoryInterface Any implementation of a ResponseFactory
  12. * @param ContainerInterface|null Any implementation of a Container
  13. * @param CallableResolverInterface|null Any implementation of a CallableResolver
  14. * @param RouteCollectorInterface|null Any implementation of a RouteCollector
  15. * @param RouteResolverInterface|null Any implementation of a RouteResolver
  16. */
  17. $app = new App(...);

Removed App Settings

Changes to Container

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.

Changes to Routing components

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 intoRouteCollector, RouteParser and RouteResolver. Those 3 components can all have their respective interfaces which you can implement on your own and inject intothe App constructor. The following pull requests offer a lot of insight on the public interfaces of these new components:

New Middleware Approach

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.

Middleware Execution

Middleware execution has not changed and is still Last In First Out (LIFO) like in Slim 3.

New App Factory

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-7implementation and ServerRequest creator is installed in your project root and enables you to instantiate an app via AppFactory::create() and use App::run() withouthaving to pass in a ServerRequest object. The following PSR-7 implementations and ServerRequest creator combos are supported:

New Routing Middleware

The routing has been implemented as middleware. We are still using 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 for more information.

  1. <?php
  2. use Slim\Factory\AppFactory;
  3. require __DIR__ . '/../vendor/autoload.php';
  4. $app = AppFactory::create();
  5. // Add Routing Middleware
  6. $app->addRoutingMiddleware();
  7. // ...
  8. $app->run();

New Error Handling Middleware

Error handling has also been implemented as middleware.See Pull Request #2398 for more information.

  1. <?php
  2. use Slim\Factory\AppFactory;
  3. require __DIR__ . '/../vendor/autoload.php';
  4. $app = AppFactory::create();
  5. /*
  6. * The routing middleware should be added before the ErrorMiddleware
  7. * Otherwise exceptions thrown from it will not be handled
  8. */
  9. $app->addRoutingMiddleware();
  10. /*
  11. * Add Error Handling Middleware
  12. *
  13. * @param bool $displayErrorDetails -> Should be set to false in production
  14. * @param bool $logErrors -> Parameter is passed to the default ErrorHandler
  15. * @param bool $logErrorDetails -> Display error details in error log
  16. * which can be replaced by a callable of your choice.
  17. * Note: This middleware should be added last. It will not handle any exceptions/errors
  18. * for middleware added after it.
  19. */
  20. $app->addErrorMiddleware(true, true, true);
  21. // ...
  22. $app->run();

New Dispatcher & Routing Results

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 for more information.

  1. <?php
  2. use Psr\Http\Message\ResponseInterface as Response;
  3. use Psr\Http\Message\ServerRequestInterface as Request;
  4. use Slim\Factory\AppFactory;
  5. use Slim\Routing\RouteContext;
  6. require __DIR__ . '/../vendor/autoload.php';
  7. $app = AppFactory::create();
  8. $app->get('/hello/{name}', function (Request $request, Response $response) {
  9. $routeContext = RouteContext::fromRequest($request);
  10. $routingResults = $routeContext->getRoutingResults();
  11. // Get all of the route's parsed arguments e.g. ['name' => 'John']
  12. $routeArguments = $routingResults->getRouteArguments();
  13. // A route's allowed methods are available at all times now and not only when an error arises like in Slim 3
  14. $allowedMethods = $routingResults->getAllowedMethods();
  15. return $response;
  16. });
  17. // ...
  18. $app->run();

New Method Overriding Middleware

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 for more information.

  1. <?php
  2. use Slim\Factory\AppFactory;
  3. use Slim\Middleware\MethodOverridingMiddleware;
  4. require __DIR__ . '/../vendor/autoload.php';
  5. $app = AppFactory::create();
  6. $methodOverridingMiddleware = new MethodOverridingMiddleware();
  7. $app->add($methodOverridingMiddleware);
  8. // ...
  9. $app->run();

New Content Length Middleware

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.

  1. <?php
  2. use Slim\Factory\AppFactory;
  3. use Slim\Middleware\ContentLengthMiddleware;
  4. require __DIR__ . '/../vendor/autoload.php';
  5. $app = AppFactory::create();
  6. $contentLengthMiddleware = new ContentLengthMiddleware();
  7. $app->add($contentLengthMiddleware);
  8. // ...
  9. $app->run();

New Output Buffering Middleware

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.

  1. <?php
  2. use Slim\Factory\AppFactory;
  3. use Slim\Middleware\OutputBufferingMiddleware;
  4. require __DIR__ . '/../vendor/autoload.php';
  5. $app = AppFactory::create();
  6. /**
  7. * The two modes available are
  8. * OutputBufferingMiddleware::APPEND (default mode) - Appends to existing response body
  9. * OutputBufferingMiddleware::PREPEND - Creates entirely new response body
  10. */
  11. $mode = OutputBufferingMiddleware::APPEND;
  12. $outputBufferingMiddleware = new OutputBufferingMiddleware($mode);
  13. // ...
  14. $app->run();