The Role of Middleware in PHP Frameworks

Vitaliy Dotsenko
Legacybeta
Published in
3 min readApr 29, 2020
Original photo by K8 on Unsplash

The middleware in web applications is the mid-layer between the HTTP request and the application logic. The middleware process incoming requests and execute the code before the controller’s actions. One of the main functions is filtering HTTP requests from the user’s browser before the actual application logic.

Frequently the middleware layer has multiply middlewares in the chain and they run one after another. This chaining of the middlewares allow you to break up your code and create reusable middlewares. Each middleware has access to the HTTP request with payload and each middleware can either delegate the request to the next middleware or another layer of the application or just return the response. Returning the response prevents the lower layers from ever getting the request.

You can imagine the middlewares layer in an application like an onion, the middleware layers wrap up your application logic:

The Middleware Onion

Typical use cases of the middleware are:

  • User authorization;
  • Logging;
  • Handling exceptions;
  • Rate-limiting incoming HTTP requests;
  • Handling CORS;
  • Encrypted Cookies;
  • CSRF protection.

User authorization

After the user is authenticated, usually with login and password, you can use the middleware layer to check their authorization. In other words, checking what the user or the group can or can’t do.

Logging

With the middleware you can easily create central logging for the incoming requests with additional information like client IP address, HTTP request headers, and request payload.

Handling exceptions

The middleware layer can allow you to handle code exceptions above the controller layer. Of course, you can do it in the controllers but in this case, you’ll have code duplicates and violate the DRY principle.

Rate-limiting incoming HTTP requests

Middleware is good for limiting how often individual IP addresses can make requests to your application in order to prevent spam or DDoS attacks.

Handling CORS

In some frameworks, you can setup CORS middleware to accept only specific origins and headers. The middleware provides a good place to apply or check HTTP headers that relate to CORS.

Encrypted Cookies

Because the middleware has direct access to the HTTP request and response it’s possible to encrypt the cookies on the server before sending HTTP response to the user and decrypt the cookies after getting it back from the user.

CSRF protection

The middleware layer is a good place to implement defense against CSRF (Cross Site Request Forgery) attacks. To prevent these attacks commonly uses a random CSRF token that is stored on the server using PHP session or the database, then this token should be embedded in POST or GET or passed as HTTP header. Lastly, you can just check the token in the middleware.

PHP frameworks implement the middleware logic differently. The main PHP specification is called PSR (PHP Standard Recommendation). You probably have heard about the PHP coding style — PSR-1: Basic Coding Standard. However, in PSR standards you can also find another standard that is related to middleware.

The PSR-15: HTTP Server Request Handlers standard describe common interfaces for HTTP request handlers and middlewares that use HTTP messages. This document has the definition of the interface Psr\Http\ServerMiddlewareInterface and the middleware which uses this PHP standard must implement it and return an instance of Psr\Http\Message\ResponseInterface. Each middleware should invoke the next middleware and pass it request and response objects as arguments.

Middleware framework Mezzio (ex Zend Expressie) has implemented the standard PSR-15 and it allows you to write middlewares based on PSR-15 standard.

If you’re looking for a way to stack your PHP middlewares together have a look at the Stack project. There you can find a lot of middleware implementations for different use cases in your project.

The middleware layer is not unique to PHP frameworks or the language. Django Framework from Python, Express and Koa in JavaScript/Node.js, Spring Framework in Java (Spring developers call it Interceptor) all have middleware layers.

The middleware layer improves the stability and the speed of the response of an application. It is comparably easy to write and maintain as your application logic.

--

--

Vitaliy Dotsenko
Legacybeta

I like coding, open-source software and hi-tech 🚀