Skip to Content
Course content

38: Middleware Concepts Across PHP Frameworks

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Wait, so is middleware just a fancy word for a filter?

Essentially, yes. But think of it less like a coffee filter and more like an onion. When a request hits your application, it doesn't just jump straight to your controller. It has to pass through these layers of middleware first. I like to imagine it as a series of security checkpoints at an airport. The first guy checks your ID, the second checks your bags, and only after you've passed both do you actually get to the gate (your controller).

Let's use a real-world example: API Key Validation. You don't want to write the code to check for a valid X-API-KEY header inside every single one of your controller methods. That's a maintenance nightmare. Instead, you wrap those routes in a piece of middleware that handles the check once. If the key is missing or wrong, the middleware just returns a 401 Unauthorized response immediately, and your controller never even knows a request was attempted.

How does the request actually move through the chain without getting stuck?

This is where learners usually get tripped up. The secret is a "callback" or a "next" handler. In most PHP frameworks—Laravel is the most prominent example here—the middleware receives the request and a closure (usually called $next). If the middleware is happy with the request, it calls $next($request). That call is what pushes the request deeper into the onion to the next layer.

public function handle($request, Closure $next)
{
    // 1. Pre-processing: Check the API key
    if ($request->header('X-API-KEY') !== 'secret-123') {
        return response('Invalid API Key', 401);
    }

    // 2. Pass the request to the next layer of the onion
    return $next($request);
}

If you forget to return $next($request), your application will simply stop there. You'll get a blank screen or a null response because you've effectively broken the chain.

Can I modify the response on the way back out, or is it only for blocking requests?

You absolutely can. This is one of the coolest parts of the middleware pattern. Because the $next($request) call returns the response from the deeper layers, you can capture that response, tweak it, and then send it back up the chain. I often use this for adding custom security headers or logging how long a request took to process.

Notice the difference in structure here; the logic happens after the call to the next layer:

public function handle($request, Closure $next)
{
    // Let the request go all the way to the controller and back
    $response = $next($request);

    // Post-processing: Now we are on the way "out"
    $response->headers->set('X-Processed-By', 'MyCustomMiddleware');
    
    return $response;
}

Do I have to relearn this for every single PHP framework?

Not really. While Laravel, Symfony, and Slim have slightly different syntax, the industry has largely converged on a standard called PSR-15 (PHP Standard Recommendation). PSR-15 defines a common interface for middleware, meaning the core concept—a Request goes in, a Response comes out—is universal.

If you understand the "onion" flow and the concept of the "next" handler, you can jump between these frameworks with very little friction. You'll just be looking for where the framework tells you to "register" the middleware (like a Kernel.php file in Laravel or a middleware.php file in Slim).




📋 Practical Task

Implementing a Maintenance Mode Middleware

Your task is to create a middleware class that simulates a "Maintenance Mode" for an application. Instead of hardcoding a boolean, the middleware should check if a specific file exists on the server's disk (e.g., storage/framework/maintenance.lock).

  • If the maintenance.lock file exists, the middleware should intercept the request and return a 503 Service Unavailable response with the message "Site is currently under maintenance. Please try again later."
  • If the file does not exist, the middleware should allow the request to proceed to the next layer of the application.
  • Ensure your code correctly handles the $next closure to avoid breaking the request chain.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.