Routing

The Slim Framework’s router is built on top of the Fast Route component, and it is remarkably fast and stable.While we are using this component to do all our routing, the app’s core has been entirely decoupled from it and interfaces have been put in place topave the way for using other routing libraries.

How to create routes

You can define application routes using proxy methods on the Slim\App instance. The Slim Framework provides methods for the most popular HTTP methods.

GET Route

You can add a route that handles only GET HTTP requests with the Slimapplication’s get() method. It accepts two arguments:

  • The route pattern (with optional named placeholders)
  • The route callback
  1. $app->get('/books/{id}', function ($request, $response, $args) {
  2. // Show book identified by $args['id']
  3. });

POST Route

You can add a route that handles only POST HTTP requests with the Slimapplication’s post() method. It accepts two arguments:

  • The route pattern (with optional named placeholders)
  • The route callback
  1. $app->post('/books', function ($request, $response, $args) {
  2. // Create new book
  3. });

PUT Route

You can add a route that handles only PUT HTTP requests with the Slimapplication’s put() method. It accepts two arguments:

  • The route pattern (with optional named placeholders)
  • The route callback
  1. $app->put('/books/{id}', function ($request, $response, $args) {
  2. // Update book identified by $args['id']
  3. });

DELETE Route

You can add a route that handles only DELETE HTTP requests with the Slimapplication’s delete() method. It accepts two arguments:

  • The route pattern (with optional named placeholders)
  • The route callback
  1. $app->delete('/books/{id}', function ($request, $response, $args) {
  2. // Delete book identified by $args['id']
  3. });

OPTIONS Route

You can add a route that handles only OPTIONS HTTP requests with the Slimapplication’s options() method. It accepts two arguments:

  • The route pattern (with optional named placeholders)
  • The route callback
  1. $app->options('/books/{id}', function ($request, $response, $args) {
  2. // Return response headers
  3. });

PATCH Route

You can add a route that handles only PATCH HTTP requests with the Slimapplication’s patch() method. It accepts two arguments:

  • The route pattern (with optional named placeholders)
  • The route callback
  1. $app->patch('/books/{id}', function ($request, $response, $args) {
  2. // Apply changes to book identified by $args['id']
  3. });

Any Route

You can add a route that handles all HTTP request methods with the Slim application’s any() method. It accepts two arguments:

  • The route pattern (with optional named placeholders)
  • The route callback
  1. $app->any('/books/[{id}]', function ($request, $response, $args) {
  2. // Apply changes to books or book identified by $args['id'] if specified.
  3. // To check which method is used: $request->getMethod();
  4. });

Note that the second parameter is a callback. You could specify a Class which implementes the __invoke() method instead of a Closure. You can then do the mapping somewhere else:

  1. $app->any('/user', 'MyRestfulController');

Custom Route

You can add a route that handles multiple HTTP request methods with the Slim application’s map() method. It accepts three arguments:

  • Array of HTTP methods
  • The route pattern (with optional named placeholders)
  • The route callback
  1. $app->map(['GET', 'POST'], '/books', function ($request, $response, $args) {
  2. // Create new book or list all books
  3. });

Route callbacks

Each routing method described above accepts a callback routine as its final argument. This argument can be any PHP callable, and by default it accepts three arguments.

  • Request The first argument is a Psr\Http\Message\ServerRequestInterface object that represents the current HTTP request.
  • Response The second argument is a Psr\Http\Message\ResponseInterface object that represents the current HTTP response.
  • Arguments The third argument is an associative array that contains values for the current route’s named placeholders.

Writing content to the response

There are two ways you can write content to the HTTP response. First, you can simply echo() content from the route callback. This content will be appended to the current HTTP response object. Second, you can return a Psr\Http\Message\ResponseInterface object.

Closure binding

If you use a dependency container and a Closure instance as the route callback, the closure’s state is bound to the Container instance. This means you will have access to the DI container instance inside of the Closure via the $this keyword:

  1. $app->get('/hello/{name}', function ($request, $response, $args) {
  2. // Use app HTTP cookie service
  3. $this->get('cookies')->set('name', [
  4. 'value' => $args['name'],
  5. 'expires' => '7 days'
  6. ]);
  7. });

Heads Up!

Slim does not support static closures.

Redirect helper

You can add a route that redirects GET HTTP requests to a different URL withthe Slim application’s redirect() method. It accepts three arguments:

  • The route pattern (with optional named placeholders) to redirect from
  • The location to redirect to, which may be a string or aPsr\Http\Message\UriInterface
  • The HTTP status code to use (optional; 302 if unset)
  1. $app->redirect('/books', '/library', 301);

redirect() routes respond with the status code requested and a Locationheader set to the second argument.

Route strategies

The route callback signature is determined by a route strategy. By default, Slim expects route callbacks to accept the request, response, and an array of route placeholder arguments. This is called the RequestResponse strategy. However, you can change the expected route callback signature by simply using a different strategy. As an example, Slim provides an alternative strategy called RequestResponseArgs that accepts request and response, plus each route placeholder as a separate argument.

Here is an example of using this alternative strategy:

  1. <?php
  2. use Slim\Factory\AppFactory;
  3. use Slim\Handlers\Strategies\RequestResponseArgs;
  4. require __DIR__ . '/../vendor/autoload.php';
  5. $app = AppFactory::create();
  6. /**
  7. * Changing the default invocation strategy on the RouteCollector component
  8. * will change it for every route being defined after this change being applied
  9. */
  10. $routeCollector = $app->getRouteCollector();
  11. $routeCollector->setDefaultInvocationStrategy(new RequestResponseArgs());
  12. $app->get('/hello/{name}', function ($request, $response, $name) {
  13. return $response->write($name);
  14. });

Alternatively you can set a different invocation strategy on a per route basis:

  1. <?php
  2. use Slim\Factory\AppFactory;
  3. use Slim\Handlers\Strategies\RequestResponseArgs;
  4. require __DIR__ . '/../vendor/autoload.php';
  5. $app = AppFactory::create();
  6. $routeCollector = $app->getRouteCollector();
  7. $route = $app->get('/hello/{name}', function ($request, $response, $name) {
  8. return $response->write($name);
  9. });
  10. $route->setInvocationStrategy(new RequestResponseArgs());

You can provide your own route strategy by implementing the Slim\Interfaces\InvocationStrategyInterface.

Route placeholders

Each routing method described above accepts a URL pattern that is matched against the current HTTP request URI. Route patterns may use named placeholders to dynamically match HTTP request URI segments.

Format

A route pattern placeholder starts with a {, followed by the placeholder name, ending with a }. This is an example placeholder named name:

  1. $app->get('/hello/{name}', function (Request $request, Response $response, $args) {
  2. $name = $args['name'];
  3. echo "Hello, $name";
  4. });

Optional segments

To make a section optional, simply wrap in square brackets:

  1. $app->get('/users[/{id}]', function ($request, $response, $args) {
  2. // responds to both `/users` and `/users/123`
  3. // but not to `/users/`
  4. });

Multiple optional parameters are supported by nesting:

  1. $app->get('/news[/{year}[/{month}]]', function ($request, $response, $args) {
  2. // reponds to `/news`, `/news/2016` and `/news/2016/03`
  3. });

For “Unlimited” optional parameters, you can do this:

  1. $app->get('/news[/{params:.*}]', function ($request, $response, $args) {
  2. // $params is an array of all the optional segments
  3. $params = explode('/', $args['params']);
  4. });

In this example, a URI of /news/2016/03/20 would result in the $params arraycontaining three elements: ['2016', '03', '20'].

Regular expression matching

By default the placeholders are written inside {} and can accept anyvalues. However, placeholders can also require the HTTP request URI to match a particular regular expression. If the current HTTP request URI does not match a placeholder regular expression, the route is not invoked. This is an example placeholder named id that requires one or more digits.

  1. $app->get('/users/{id:[0-9]+}', function ($request, $response, $args) {
  2. // Find user identified by $args['id']
  3. });

Route names

Application routes can be assigned a name. This is useful if you want to programmatically generate a URL to a specific route with the RouteParser’s urlFor() method. Each routing method described above returns a Slim\Route object, and this object exposes a setName() method.

  1. $app->get('/hello/{name}', function ($request, $response, $args) {
  2. echo "Hello, " . $args['name'];
  3. })->setName('hello');

You can generate a URL for this named route with the application RouteParser’s urlFor() method.

  1. $routeParser = $app->getRouteCollector()->getRouteParser();
  2. echo $routeParser->urlFor('hello', ['name' => 'Josh'], ['example' => 'name']);
  3. // Outputs "/hello/Josh?example=name"

The RouteParser’s urlFor() method accepts three arguments:

  • $routeName The route name. A route’s name can be set via $route->setName('name'). Route mapping methods return an instance of Route so you can set the name directly after mapping the route. e.g.: $app->get('/', function () {…})->setName('name')
  • $data Associative array of route pattern placeholders and replacement values.
  • $queryParams Associative array of query parameters to be appended to the generated url.

Route groups

To help organize routes into logical groups, the Slim\App also provides a group() method. Each group’s route pattern is prepended to the routes or groups contained within it, and any placeholder arguments in the group pattern are ultimately made available to the nested routes:

  1. $app->group('/users/{id:[0-9]+}', function (RouteCollectorProxy $group) {
  2. $group->map(['GET', 'DELETE', 'PATCH', 'PUT'], '', function ($request, $response, $args) {
  3. // Find, delete, patch or replace user identified by $args['id']
  4. })->setName('user');
  5. $group->get('/reset-password', function ($request, $response, $args) {
  6. // Route for /users/{id:[0-9]+}/reset-password
  7. // Reset the password for user identified by $args['id']
  8. })->setName('user-password-reset');
  9. });

The group pattern can be empty, enabling the logical grouping of routes that do not share a common pattern.

  1. $app->group('', function (RouteCollectorProxy $group) {
  2. $group->get('/billing', function ($request, $response, $args) {
  3. // Route for /billing
  4. });
  5. $group->get('/invoice/{id:[0-9]+}', function ($request, $response, $args) {
  6. // Route for /invoice/{id:[0-9]+}
  7. });
  8. })->add(new GroupMiddleware());

Note inside the group closure, Slim binds the closure to the container instance.

  • inside route closure, $this is bound to the instance of Psr\Container\ContainerInterface

Route middleware

You can also attach middleware to any route or route group.

  1. $app->group('/foo', function (RouteCollectorProxy $group) {
  2. $group->get('/bar', function ($request, $response, $args) {
  3. })->add(new RouteMiddleware());
  4. })->add(new GroupMiddleware());

Route expressions caching

It’s possible to enable router cache via RouteCollector::setCacheFile(). See examples below:

  1. <?php
  2. use Slim\Factory\AppFactory;
  3. require __DIR__ . '/../vendor/autoload.php';
  4. $app = AppFactory::create();
  5. /**
  6. * To generate the route cache data, you need to set the file to one that does not exist in a writable directory.
  7. * After the file is generated on first run, only read permissions for the file are required.
  8. *
  9. * You may need to generate this file in a development environment and comitting it to your project before deploying
  10. * if you don't have write permissions for the directory where the cache file resides on the server it is being deployed to
  11. */
  12. $routeCollector = $app->getRouteCollector();
  13. $routeCollector->setCacheFile('/path/to/cache.file');

Container Resolution

You are not limited to defining a function for your routes. In Slim there are a few different ways to define your route action functions.

In addition to a function, you may use:

  • container_key:method
  • Class:method
  • Class implementing __invoke() method
  • container_keyThis functionality is enabled by Slim’s Callable Resolver Class. It translates a string entry into a function call.Example:
  1. $app->get('/', '\HomeController:home');

Alternatively, you can take advantage of PHP’s ::class operator which works well with IDE lookup systems and produces the same result:

  1. $app->get('/', \HomeController::class . ':home');

In this code above we are defining a / route and telling Slim to execute the home() method on the HomeController class.

Slim first looks for an entry of HomeController in the container, if it’s found it will use that instance otherwise it will call it’s constructor with the container as the first argument. Once an instance of the class is created it will then call the specified method using whatever Strategy you have defined.

Registering a controller with the container

Create a controller with the home action method. The constructor should acceptthe dependencies that are required. For example:

  1. <?php
  2. class HomeController
  3. {
  4. protected $view;
  5. public function __construct(\Slim\Views\Twig $view) {
  6. $this->view = $view;
  7. }
  8. public function home($request, $response, $args) {
  9. // your code here
  10. // use $this->view to render the HTML
  11. return $response;
  12. }
  13. }

Create a factory in the container that instantiates the controller with the dependencies:

  1. $container = $app->getContainer();
  2. $container->set('HomeController', function (ContainerInterface $c) {
  3. $view = $c->get('view'); // retrieve the 'view' from the container
  4. return new HomeController($view);
  5. });

This allows you to leverage the container for dependency injection and so you caninject specific dependencies into the controller.

Allow Slim to instantiate the controller

Alternatively, if the class does not have an entry in the container, then Slimwill pass the container’s instance to the constructor. You can construct controllerswith many actions instead of an invokable class which only handles one action.

  1. <?php
  2. use Psr\Container\ContainerInterface;
  3. class HomeController
  4. {
  5. protected $container;
  6. // constructor receives container instance
  7. public function __construct(ContainerInterface $container) {
  8. $this->container = $container;
  9. }
  10. public function home($request, $response, $args) {
  11. // your code
  12. // to access items in the container... $this->container->get('');
  13. return $response;
  14. }
  15. public function contact($request, $response, $args) {
  16. // your code
  17. // to access items in the container... $this->container->get('');
  18. return $response;
  19. }
  20. }

You can use your controller methods like so.

  1. $app->get('/', \HomeController::class . ':home');
  2. $app->get('/contact', \HomeController::class . ':contact');

Using an invokable class

You do not have to specify a method in your route callable and can just set it to be an invokable class such as:

  1. <?php
  2. use Psr\Container\ContainerInterface;
  3. class HomeAction
  4. {
  5. protected $container;
  6. public function __construct(ContainerInterface $container) {
  7. $this->container = $container;
  8. }
  9. public function __invoke($request, $response, $args) {
  10. // your code
  11. // to access items in the container... $this->container->get('');
  12. return $response;
  13. }
  14. }

You can use this class like so.

  1. $app->get('/', \HomeAction::class);

Again, as with controllers, if you register the class name with the container, then youcan create a factory and inject just the specific dependencies that you require into youraction class.