The Middleware Interface
Apivalk middleware is PSR-15 middleware. Every middleware implementsPsr\Http\Server\MiddlewareInterface:
$request: The PSR-7 server request.$handler: The rest of the pipeline. Call$handler->handle($request)to hand the request on.
Apivalk context
Middleware in the routed stack reads what Apivalk knows about the request withApivalkContext::fromRequest($request):
getRoute(): the route as the controller’sgetRoute()declares it.getControllerClass(): the controller class.getRequest(): the typedApivalkRequestInterface(header(),query(),body(),path(),getAuthIdentity(),setAuthIdentity(),getLocale(),getIp(), …).getApivalkTraceId(): the id Apivalk gave the request, see Trace id.respond(AbstractApivalkResponse $response): turns a typed response into the PSR-7 response to return, e.g.return $context->respond(new UnauthorizedApivalkResponse());.
ApivalkContext::fromRequest() throws a LogicException outside the routed stack. A global middleware still gets the trace id with ApivalkTraceId::fromRequest($request), e.g. for an access log that every response passes, the 404 and the 500 included:
What reaches the controller
The typed request is populated before the routed middleware run, so awithHeader() or withAttribute() there does not change its bags. The controller still sees it: $request->getServerRequest() returns the PSR-7 request as the last middleware handed it on, e.g. $request->getServerRequest()->getAttribute('request_id').
The body stream is rewound after population, so a middleware can read the raw body with $request->getBody()->getContents().
Middleware Stacks
ApivalkConfiguration has two MiddlewareStacks. Both take middleware with add() and run them in the order they were added.
Onion Execution Pattern
Each middleware wraps everything added after it.- Request Phase: The first middleware added sees the request first and runs its logic before calling
$handler->handle($request). - Next Call: This continues until the last middleware hands the request to the controller.
- Response Phase: The controller’s response travels back through the middleware in reverse order, so the first middleware added sees the response last and can replace it (PSR-7 responses are immutable, use
withHeader()and friends).
Configuration
Middlewares are typically configured via theApivalkConfiguration object during the bootstrapping phase.
Built-in Middlewares
Apivalk comes with several essential middlewares out of the box.AuthenticationMiddleware, SecurityMiddleware and RateLimitMiddleware are final readonly, so wrap them in a middleware of your own instead of extending them:
See Security Responsibilities for what validation cannot catch and what your application is responsible for.