Middleware

You can run code before and after your Slim application to manipulate theRequest and Response objects as you see fit. This is called middleware.Why would you want to do this? Perhaps you want to protect your appfrom cross-site request forgery. Maybe you want to authenticate requestsbefore your app runs. Middleware is perfect for these scenarios.

What is middleware?

Technically speaking, a middleware is a callable that accepts three arguments:

  • \Psr\Http\Message\ServerRequestInterface - The PSR7 request object
  • \Psr\Http\Message\ResponseInterface - The PSR7 response object
  • callable - The next middleware callableIt can do whatever is appropriate with these objects. The only hard requirementis that a middleware MUST return an instance of \Psr\Http\Message\ResponseInterface.Each middleware SHOULD invoke the next middleware and pass it Request andResponse objects as arguments.

How does middleware work?

Different frameworks use middleware differently. Slim adds middleware as concentriclayers surrounding your core application. Each new middleware layer surroundsany existing middleware layers. The concentric structure expands outwardly asadditional middleware layers are added.

The last middleware layer added is the first to be executed.

When you run the Slim application, the Request and Response objects traverse themiddleware structure from the outside in. They first enter the outer-most middleware,then the next outer-most middleware, (and so on), until they ultimately arriveat the Slim application itself. After the Slim application dispatches theappropriate route, the resultant Response object exits the Slim application andtraverses the middleware structure from the inside out. Ultimately, a finalResponse object exits the outer-most middleware, is serialized into a raw HTTPresponse, and is returned to the HTTP client. Here’s a diagram that illustratesthe middleware process flow:

Middleware architecture

How do I write middleware?

Middleware is a callable that accepts three arguments: a Request object, a Response object, and the next middleware. Each middleware MUST return an instance of \Psr\Http\Message\ResponseInterface.

Closure middleware example.

This example middleware is a Closure.

  1. <?php
  2. /**
  3. * Example middleware closure
  4. *
  5. * @param \Psr\Http\Message\ServerRequestInterface $request PSR7 request
  6. * @param \Psr\Http\Message\ResponseInterface $response PSR7 response
  7. * @param callable $next Next middleware
  8. *
  9. * @return \Psr\Http\Message\ResponseInterface
  10. */
  11. function ($request, $response, $next) {
  12. $response->getBody()->write('BEFORE');
  13. $response = $next($request, $response);
  14. $response->getBody()->write('AFTER');
  15. return $response;
  16. };

Invokable class middleware example

This example middleware is an invokable class that implements the magic __invoke() method.

  1. <?php
  2. class ExampleMiddleware
  3. {
  4. /**
  5. * Example middleware invokable class
  6. *
  7. * @param \Psr\Http\Message\ServerRequestInterface $request PSR7 request
  8. * @param \Psr\Http\Message\ResponseInterface $response PSR7 response
  9. * @param callable $next Next middleware
  10. *
  11. * @return \Psr\Http\Message\ResponseInterface
  12. */
  13. public function __invoke($request, $response, $next)
  14. {
  15. $response->getBody()->write('BEFORE');
  16. $response = $next($request, $response);
  17. $response->getBody()->write('AFTER');
  18. return $response;
  19. }
  20. }

To use this class as a middleware, you can use ->add( new ExampleMiddleware() ); function chain after the $app, Route, or group(), which in the code below, any one of these, could represent $subject.

  1. $subject->add( new ExampleMiddleware() );

How do I add middleware?

You may add middleware to a Slim application, to an individual Slim application route or to a route group. All scenarios accept the same middleware and implement the same middleware interface.

Application middleware

Application middleware is invoked for every incoming HTTP request. Add application middleware with the Slim application instance’s add() method. This example adds the Closure middleware example above:

  1. <?php
  2. $app = new \Slim\App();
  3. $app->add(function ($request, $response, $next) {
  4. $response->getBody()->write('BEFORE');
  5. $response = $next($request, $response);
  6. $response->getBody()->write('AFTER');
  7. return $response;
  8. });
  9. $app->get('/', function ($request, $response, $args) {
  10. $response->getBody()->write(' Hello ');
  11. return $response;
  12. });
  13. $app->run();

This would output this HTTP response body:

  1. BEFORE Hello AFTER

Route middleware

Route middleware is invoked only if its route matches the current HTTP request method and URI. Route middleware is specified immediately after you invoke any of the Slim application’s routing methods (e.g., get() or post()). Each routing method returns an instance of \Slim\Route, and this class provides the same middleware interface as the Slim application instance. Add middleware to a Route with the Route instance’s add() method. This example adds the Closure middleware example above:

  1. <?php
  2. $app = new \Slim\App();
  3. $mw = function ($request, $response, $next) {
  4. $response->getBody()->write('BEFORE');
  5. $response = $next($request, $response);
  6. $response->getBody()->write('AFTER');
  7. return $response;
  8. };
  9. $app->get('/', function ($request, $response, $args) {
  10. $response->getBody()->write(' Hello ');
  11. return $response;
  12. })->add($mw);
  13. $app->run();

This would output this HTTP response body:

  1. BEFORE Hello AFTER

Group Middleware

In addition to the overall application, and standard routes being able to accept middleware, the group() multi-route definition functionality, also allows individual routes internally. Route group middleware is invoked only if its route matches one of the defined HTTP request methods and URIs from the group. To add middleware within the callback, and entire-group middleware to be set by chaining add() after the group() method.

Sample Application, making use of callback middleware on a group of url-handlers

  1. <?php
  2. require_once __DIR__.'/vendor/autoload.php';
  3. $app = new \Slim\App();
  4. $app->get('/', function ($request, $response) {
  5. return $response->getBody()->write('Hello World');
  6. });
  7. $app->group('/utils', function () use ($app) {
  8. $app->get('/date', function ($request, $response) {
  9. return $response->getBody()->write(date('Y-m-d H:i:s'));
  10. });
  11. $app->get('/time', function ($request, $response) {
  12. return $response->getBody()->write(time());
  13. });
  14. })->add(function ($request, $response, $next) {
  15. $response->getBody()->write('It is now ');
  16. $response = $next($request, $response);
  17. $response->getBody()->write('. Enjoy!');
  18. return $response;
  19. });

When calling the /utils/date method, this would output a string similar to the below

  1. It is now 2015-07-06 03:11:01. Enjoy!

visiting /utils/time would output a string similar to the below

  1. It is now 1436148762. Enjoy!

but visiting / (domain-root), would be expected to generate the following output as no middleware has been assigned

  1. Hello World

Passing variables from middleware

The easiest way to pass attributes from middleware is to use the request’sattributes.

Setting the variable in the middleware:

  1. $request = $request->withAttribute('foo', 'bar');

Getting the variable in the route callback:

  1. $foo = $request->getAttribute('foo');

Finding available middleware

You may find a PSR-7 Middleware class already written that will satisfy your needs. Here are a few unofficial lists to search.