Middleware is code that exists between the request and response, and which can take the incoming request, perform actions based on it, and either complete the response or pass delegation on to the next middleware in the queue.

The purpose of middleware

Middleware makes it easier for software developers to implement communication and input/output, so they can focus on the specific purpose of their application. In web services the Input represents the Request received, and Output represents the Response to be sent.

Using middleware

Middleware can be used to, but is not limited to, the following purposes:

  • A/B Testing
  • Debugging
  • Caching
  • CORS
  • Authentication (HTTP Basic Auth, OAuth 2.0, OpenID)
  • CSRF Protection
  • Rate Limiting
  • Referrals
  • IP Restriction

Usage

According to PSR-15: HTTP Server Request Handlers, a component that processes an incoming request and generates a response is a middleware. To be compliant with the PSR-15 standard, the middleware must implement Psr\Http\Server\MiddlewareInterface.

class MyMiddleware implements MiddlewareInterface

The middleware class must then implement the process method.

public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface;

Below is an example implementation of a middleware which processes the request.

class ExampleMiddleware implements MiddlewareInterface
{
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        //process request

        return $handler->handle($request);
    }
}

This is an example implementation of a middleware which processes the response.

class ExampleMiddleware implements MiddlewareInterface
{
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $response = $handler->handle($request);

        //process response 

        return $response;
    }
}

This approach processes both the request and response.

class ExampleMiddleware implements MiddlewareInterface
{
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        //process request

        $response = $handler->handle($request);

        //process response 

        return $response;
    }
}

How middleware is called

The application pipeline defines the execution flow. The request passes through the middleware in the pipeline, one by one, in the order they are placed in the pipeline. Each middleware processes the request and/or response and either passes control to the next middleware in the chain or it terminates the request and returns a reponse.

  • If control passes through all middleware successfully, the execution is eventually passed to your custom code which generates a response of its own. The execution then passes through the middleware in reverse order and returns the response.
  • If the execution is terminated before reaching your custom code (e.g. via an exception), then the response is generated by the last middleware reached by the execution.

Middleware in practice

A simple real world example of middleware usage can be the enhancement of a request with the user IP for logging porposes or building reports based on geographical data. For this example the pipeline has a single middleware.

The flow begins with a request. The execution passes the control to the IP middleware which enhances the request with the user’s IP and other relevant data. The control passes to your custom handler that processes the request and returns a response. The flow continues in reverse order, back to the IP middleware which can, if needed, change the output before it gets returned to the user that initiated the request.

Additional resources:


Looking for PHP, Laminas or Mezzio Support?

As part of the Laminas Commercial Vendor Program, Apidemia offers expert technical support and services for:

  • Migration from Laminas MVC to Mezzio or Dotkernel Headless Platform.
  • Migration from legacy Laminas API Tools (formerly Apigility) to Dotkernel API
  • Mezzio and Laminas Consulting and Technical Audit
  • Modernising Legacy Applications
  • Leave a Reply

    Your email address will not be published. Required fields are marked *

    You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>