Phil Sturgeon provides a good explanation on the why and how of middlewares in PHP.

Recently there has been a lot of buzz about HTTP middleware in PHP. Since PSR-7 was accepted, everyone and their friend Sherly has been knocking out middleware implementations, some of them stunning, some of them half-arsed, and some of them rolled into existing frameworks. HTTP Middleware is a wonderful thing, but the PHP-FIG is working on a specific standard for middleware, which will standardise this mess of implementations, but some folks don't seem to think that would be useful. Let's look into middleware a little closer, to show you why it's something to smile about.

https://philsturgeon.uk/2016/05/31/why-care-about-php-middleware/