Middlewares
Middleware is an intermediate layer that sits between the client request and the server response. It receives the request, can examine or modify it, and then passes it to the next step in the chain. The HTTP request passes through the middleware chain. Each middleware can:
- read the request (e.g., check tokens or cookies);
- perform actions (e.g., log an event, block access);
- modify the request or response (e.g., add headers);
- pass the request to the next middleware or interrupt the chain by immediately returning a response;
A middleware is represented by a class containing the process method. The process method receives the request and the next middleware as arguments. At this point, the chain can be interrupted or the request can be passed to the next middleware.
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
class TestMiddleware
{
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface {
//your code here
return $handler->handle($request);
}
}
After creating the middleware, you can apply it to one or more routes or to a group with the middleware method.
// single route
router()->get("/", function() {...})->middleware(\MyNamespace\TestMiddleware::class);
// routes group
router()->group("some-group", function($g) {
...
})->middleware(\MyNamespace\ToMiddleware\TestMiddleware::class);
You can apply multiple middlewares by chaining the middleware method multiple times.
The middlewares will be executed in order from outermost to innermost, starting from the outermost group, until reaching the destination route.
Read more about routing in the dedicated section.