Middleware
A middleware implements the PSR-15 Middleware Interface:
- - The PSR-7 request object
Psr\Http\Server\RequestHandlerInterface
- The PSR-15 request handler objectIt can do whatever is appropriate with these objects. The only hard requirementis that a middleware MUST return an instance ofPsr\Http\Message\ResponseInterface
.Each middleware SHOULD invoke the next middleware and pass it Request andResponse objects as arguments.
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 object traverses 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 is a callable that accepts two arguments: a Request
object and a RequestHandler
object. Each middleware MUST return an instance of Psr\Http\Message\ResponseInterface
.
This example middleware is a Closure.
Invokable class middleware example
<?php
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
use Slim\Psr7\Response;
class ExampleBeforeMiddleware
{
/**
* Example middleware invokable class
*
* @param ServerRequest $request PSR-7 request
* @param RequestHandler $handler PSR-15 request handler
*
* @return Response
*/
public function __invoke(Request $request, RequestHandler $handler): Response
{
$response = $handler->handle($request);
$existingContent = (string) $response->getBody();
$response = new Response();
$response->getBody()->write('BEFORE' . $existingContent);
}
}
<?php
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
class ExampleAfterMiddleware
{
/**
* Example middleware invokable class
*
* @param ServerRequest $request PSR-7 request
* @param RequestHandler $handler PSR-15 request handler
*
* @return Response
*/
public function __invoke(Request $request, RequestHandler $handler): Response
{
$response = $handler->handle($request);
$response->getBody()->write('AFTER');
return $response;
}
}
To use these classes as a middleware, you can use add(new ExampleMiddleware()); function chain after the $app route mapping methods get(), post(), put(), patch(), delete(), options(), any() or group(), which in the code below, any one of these, could represent $subject.
<?php
use Slim\Factory\AppFactory;
require __DIR__ . '/../vendor/autoload.php';
$app = AppFactory::create();
// Add Middleware On App
$app->add(new ExampleMiddleware());
// Add Middleware On Route
$app->get('/', function () { ... })->add(new ExampleMiddleware());
$app->group('/', function () { ... })->add(new ExampleMiddleware());
// ...
$app->run();
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 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:
This would output this HTTP response body:
BEFORE Hello World 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:
<?php
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
use Slim\Factory\AppFactory;
require __DIR__ . '/../vendor/autoload.php';
$app = AppFactory::create();
$mw = function (Request $request, RequestHandler $handler) {
$response = $handler->handle($request);
$response->getBody()->write('World');
return $response;
};
$app->get('/', function (Request $request, Response $response, $args) {
$response->getBody()->write('Hello ');
return $response;
})->add($mw);
$app->run();
This would output this HTTP response body:
Hello World
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.
When calling the /utils/date method, this would output a string similar to the below
It is now 2015-07-06 03:11:01. Enjoy!
Visiting /utils/time would output a string similar to the below
It is now 1436148762. Enjoy!
But visiting /(domain-root), would be expected to generate the following output as no middleware has been assigned
Passing variables from middleware
The easiest way to pass attributes from middleware is to use the request’sattributes.
Setting the variable in the middleware:
Getting the variable in the route callback:
$foo = $request->getAttribute('foo');
You may find a PSR-15 Middleware class already written that will satisfy your needs. Here are a few unofficial lists to search.