Upgrade Guide

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

New PHP version

Slim 3 requires PHP 5.5+

Class \Slim\Slim renamed \Slim\App

Slim 3 uses \Slim\App for the Application object usually named $app.

  1. $app = new \Slim\App();

New Route Function Signature

  1. $app->get('/', function (Request $req, Response $res, $args = []) {
  2. return $res->withStatus(400)->write('Bad Request');
  3. });

Request and response objects are no longer accessible via the Application object

As mentioned above, Slim 3 passes the Request and Response objects as arguments to the route handling function. Since they are now accessible directly in the body of a route function, request and response are no longer properties of the /Slim/App (Application object) instance.

Getting _GET and _POST variables

  1. $app->get('/', function (Request $req, Response $res, $args = []) {
  2. $myvar1 = $req->getParam('myvar'); //checks both _GET and _POST [NOT PSR-7 Compliant]
  3. $myvar2 = $req->getParsedBody()['myvar']; //checks _POST [IS PSR-7 compliant]
  4. $myvar3 = $req->getQueryParams()['myvar']; //checks _GET [IS PSR-7 compliant]
  5. });

Hooks

Hooks are no longer part of Slim as of v3. You should consider reimplementing any functionality associated with the default hooks in Slim v2 as middleware instead. If you need the ability to apply custom hooks at arbitrary points in your code (for example, within a route), you should consider a third-party package such as Symfony’s EventDispatcher or Zend Framework’s EventManager.

Removal HTTP Cache

In Slim v3 we have removed the HTTP-Caching into its own module Slim\Http\Cache.

Removal of Stop/Halt

Slim Core has removed Stop/Halt.In your applications, you should transition to using the withStatus() and withBody() methods.

Removal of autoloader

Slim::registerAutoloader() have been removed, we have fully moved to composer.

Changes to container

$app->container->singleton(…) is now $container = $app->getContainer(); $container['…'] = function () {}; Please read Pimple docs for more info

Removal of configureMode()

$app->configureMode(…) has been removed in v3.

Removal of PrettyExceptions

PrettyExceptions cause lots of issues for many people, so these have been removed.

Route::setDefaultConditions(…) has been removed

We have switched routers which enable you to keep the default conditions regex inside of the route pattern.

Changes to redirect

In Slim v2.x one would use the helper function $app->redirect(); to trigger a redirect request.In Slim v3.x one can do the same with using the Response class like so.

Example:

  1. $app->get('/', function ($req, $res, $args) {
  2. return $res->withStatus(302)->withHeader('Location', 'your-new-uri');
  3. });

Alternatively, if you want a route to redirect without any other handling, youcan use the shortcut helper function $app->redirect() as the routedefinition:

  1. $app->redirect('/', 'your-new-uri');

Middleware Signature

The middleware signature has changed from a class to a function.

New signature:

  1. use Psr\Http\Message\RequestInterface as Request;
  2. use Psr\Http\Message\ResponseInterface as Response;
  3. $app->add(function (Request $req, Response $res, callable $next) {
  4. // Do stuff before passing along
  5. $newResponse = $next($req, $res);
  6. // Do stuff after route is rendered
  7. return $newResponse; // continue
  8. });

You can still use a class:

  1. namespace My;
  2. use Psr\Http\Message\RequestInterface as Request;
  3. use Psr\Http\Message\ResponseInterface as Response;
  4. class Middleware
  5. {
  6. function __invoke(Request $req, Response $res, callable $next) {
  7. // Do stuff before passing along
  8. $newResponse = $next($req, $res);
  9. // Do stuff after route is rendered
  10. return $newResponse; // continue
  11. }
  12. }
  13. // Register
  14. $app->add(new My\Middleware());
  15. // or
  16. $app->add(My\Middleware::class);

Middleware Execution

Application middleware is executed as Last In First Executed (LIFE).

Flash Messages

Flash messages are no longer a part of the Slim v3 core but instead have been moved to seperate Slim Flash package.

Cookies

In v3.0 cookies has been removed from core. See FIG Cookies for a PSR-7 compatible cookie component.

Removal of Crypto

In v3.0 we have removed the dependency for crypto in core.

New Router

Slim now utilizes FastRoute, a new, more powerful router!

This means that the specification of route patterns has changed with named parameters now in braces and square brackets used for optional segments:

  1. // named parameter:
  2. $app->get('/hello/{name}', /*...*/);
  3. // optional segment:
  4. $app->get('/news[/{year}]', /*...*/);

Route Middleware

The syntax for adding route middleware has changed slightly.In v3.0:

  1. $app->get(…)->add($mw2)->add($mw1);

Getting the current route

The route is an attribute of the Request object in v3.0:

  1. $request->getAttribute('route');

When getting the current route in middleware, the value fordetermineRouteBeforeAppMiddleware must be set to true in the Applicationconfiguration, otherwise the getAttribute call returns null.

urlFor() is now pathFor() in the router

urlFor() has been renamed pathFor() and can be found in the router object:

  1. $app->get('/', function ($request, $response, $args) {
  2. $url = $this->router->pathFor('home');
  3. $response->write("<a href='$url'>Home</a>");
  4. return $response;
  5. })->setName('home');

Also, pathFor() is base path aware.

Container and DI … Constructing

Slim uses Pimple as a Dependency Injection Container.

  1. // index.php
  2. $app = new Slim\App(
  3. new \Slim\Container(
  4. include '../config/container.config.php'
  5. )
  6. );
  7. // Slim will grab the Home class from the container defined below and execute its index method.
  8. // If the class is not defined in the container Slim will still contruct it and pass the container as the first arugment to the constructor!
  9. $app->get('/', Home::class . ':index');
  10. // In container.config.php
  11. // We are using the SlimTwig here
  12. return [
  13. 'settings' => [
  14. 'viewTemplatesDirectory' => '../templates',
  15. ],
  16. 'twig' => [
  17. 'title' => '',
  18. 'description' => '',
  19. 'author' => ''
  20. ],
  21. 'view' => function ($c) {
  22. $view = new Twig(
  23. $c['settings']['viewTemplatesDirectory'],
  24. [
  25. 'cache' => false // '../cache'
  26. ]
  27. );
  28. // Instantiate and add Slim specific extension
  29. $view->addExtension(
  30. new TwigExtension(
  31. $c['router'],
  32. $c['request']->getUri()
  33. )
  34. );
  35. foreach ($c['twig'] as $name => $value) {
  36. $view->getEnvironment()->addGlobal($name, $value);
  37. }
  38. return $view;
  39. },
  40. Home::class => function ($c) {
  41. return new Home($c['view']);
  42. }
  43. ];

PSR-7 Objects

Request, Response, Uri & UploadFile are immutable.

This means that when you change one of these objects, the old instance is not updated.

  1. // This is WRONG. The change will not pass through.
  2. $app->add(function (Request $request, Response $response, $next) {
  3. $request->withAttribute('abc', 'def');
  4. return $next($request, $response);
  5. });
  6. // This is correct.
  7. $app->add(function (Request $request, Response $response, $next) {
  8. $request = $request->withAttribute('abc', 'def');
  9. return $next($request, $response);
  10. });

Message bodies are streams

  1. // ...
  2. $image = __DIR__ . '/huge_photo.jpg';
  3. $body = new Stream($image);
  4. $response = (new Response())
  5. ->withStatus(200, 'OK')
  6. ->withHeader('Content-Type', 'image/jpeg')
  7. ->withHeader('Content-Length', filesize($image))
  8. ->withBody($body);
  9. // ...

For text:

  1. // ...
  2. $response = (new Response())->getBody()->write('Hello world!')
  3. // Or Slim specific: Not PSR-7 compliant.
  4. $response = (new Response())->write('Hello world!');
  5. // ...