In this episode, we dive into how middleware works behind the scenes—using a simple example inspired by how frameworks like Slim or Laravel do things. We'll start off by setting up a basic project structure (a bit of Composer setup and a local PHP server), and then take a peek at the code we've got so far. Right now, the app is super basic—just dumping a value when run—but our goal is to build up a functional middleware stack.
First up, we define some middleware classes and get them wired into our app. If you’ve ever used app->add()
in Slim, you’ll recognize the pattern. Each middleware class has an __invoke
method (which is pretty common), and we gradually build out a proper stack to keep track of the order our middleware runs. You’ll see how each middleware wraps the next, almost like layers of an onion.
We create a MiddlewareStack
class, walk through how to add new middleware, and see how the stack structure actually works under the hood. It’s not about looping over an array, but rather about chaining functions (or closures) together, so every middleware gets a shot at handling the request before passing it along.
Then, to make the example a bit more interesting, we introduce a fake Request
object. You'll see how middleware can receive, modify, and pass along this request—just like in a real-life framework. We show how each middleware can tweak things (like setting a status code) and how data flows through the stack to the app at the end.
By the end of this video, you'll have a solid grasp on:
All in all, this is a great intro to the inner workings of middleware chains, giving you a clearer picture next time you’re working with middleware in any PHP framework.