Chapter 11 of 15

Middleware.

PSR-15 middleware handles shared HTTP concerns around controller execution.

The PSR-15 contract

MiddlewareInterface::process() receives the request and the next handler. Calling $handler->handle($request) continues the pipeline; returning a response without that call stops it.

RequireHeaderMiddleware.php
<?php

declare(strict_types=1);

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

final class RequireHeaderMiddleware implements MiddlewareInterface
{
    public function process(
        ServerRequestInterface $request,
        RequestHandlerInterface $handler,
    ): ResponseInterface {
        return $handler->handle($request);
    }
}

The container injects middleware dependencies through the constructor. Keep application rules unrelated to HTTP flow in services.

Attaching middleware

Add route middleware with ->middleware(ClassName::class). The same concern can be attached to an entire route group.

Route middleware
<?php

declare(strict_types=1);

$router
    ->getNamed(
        'account',
        '/account',
        ControllerAction::for(AccountController::class, 'show'),
    )
    ->middleware(RequireHeaderMiddleware::class);

Registration order controls how the handler is wrapped. Global middleware additionally runs before routing.

Detailed technical documentation on GitHub