AbstractMiddleware
The AbstractMiddleware
is a little helper for creating your own middlewares. It processes the incoming request before
handing it over to the next middleware in line, and later processes the response before returning it to the previous
middleware. Originally both methods just return their argument unchanged, so you should implement either one of them or
both as needed.
The AbstractMiddleware
implements the PsrHttpServerMiddlewareInterface
following PHP-FIG's recommendation
PSR-15: HTTP Server Request Handlers.
Properties
The AbstractMiddleware
has a single protected property AbstractMiddleware::requestHandler
referencing the request
handler which called the middleware.
The AbstractMiddleware
works with any request handler implementing the PsrHttpServerRequestHandlerInterface
, so
you can use your middlewares with other PSR-15 frameworks as well. If the request handler is a
QueueRequestHandler, the property can be used to access the request and/or response object (as properties of
the request handler) when they are otherwise not available. Other request handlers usually don't have those properties,
so check the type of the request handler first if your middleware should work with them, too.
Example:
if ($this->requestHandler instanceof QueueRequestHandler) { $request = $this->requestHandler->request; }
Methods
The AbstractMiddleware
provides one public API method and two protected methods. While the former is final and makes
sure it implements the PsrHttpServerMiddlewareInterface
, the latter are intended to be extended in your own class.
The main AbstractMiddleware::process() method implements the interface and is also called when invoking the middleware object directly. It first passes the incoming request to the AbstractMiddleware::processRequest() method, then hands over the result to the request handler to receive a response, which is then processed by AbstractMiddleware::processResponse() before returning it back to the request handler again.
Processing a Request
The default method of AbstractMiddleware
just returns the request unchanged. If you need to process the request, you
have to implement your own processRequest()
method. It takes a request object as only argument and must return a
valid request object as well. Just make sure it follows PHP-FIG's standard recommendation
PSR-7: HTTP Message Interfaces and implements the
PsrHttpMessageServerRequestInterface
.
Processing a Response
The default method of AbstractMiddleware
just returns the response unchanged. If you need to process the response,
you have to implement your own processResponse()
method. It takes a response object as only argument and must return
a valid response object as well. Just make sure it follows PHP-FIG's standard recommendation
PSR-7: HTTP Message Interfaces and implements the
PsrHttpMessageResponseInterface
.