MVC Lesson 13: Middleware in PHP MVC

In a PHP MVC framework, whether middleware is called for each request or only for specific controllers depends on how the middleware is implemented and configured in that specific framework.

✅ General Behavior of Middleware in PHP MVC

Middleware can be applied in three main ways:


1. Global Middleware (Called for Every Request)

  • Runs before or after every request, regardless of which controller or route is being accessed.
  • Often used for:
    • Session start
    • Logging
    • Authentication checks
    • CORS headers
    • Maintenance mode

Example (Laravel):

// app/Http/Kernel.php
protected $middleware = [
    \App\Http\Middleware\CheckForMaintenanceMode::class,
    \Illuminate\Session\StartSession::class,
];

These middleware run on every request.


2. Route Middleware (Called Only for Specific Routes/Controllers)

  • Applied only to routes or controllers where it’s explicitly declared.
  • Useful for:
    • Role-based access
    • Authenticated-only pages
    • CSRF protection

Example (Laravel):

Route::middleware(['auth'])->group(function () {
    Route::get('/dashboard', 'DashboardController@index');
});

Only requests that match those routes will run the auth middleware.


3. Controller Middleware (Scoped to a Specific Controller)

  • Declared inside the controller itself.
  • Gives very fine-grained control over which middleware affects which actions.

Example (Laravel):

class UserController extends Controller {
    public function __construct() {
        $this->middleware('auth');
    }
}

🔍 Summary

Middleware TypeApplies to All Requests?Can Be Scoped?
Global✅ Yes❌ No
Route-based❌ No✅ Yes
Controller-based❌ No✅ Yes

🧠 In Custom PHP MVC (Not Laravel)?

If you’re building your own framework or using a simpler one (like Slim, CodeIgniter, etc.), middleware is typically handled by:

  • A front controller (like index.php) that routes all requests
  • Middleware layers are then called manually or via a stack

You can choose to:

  • Run global middleware before routing
  • Or assign specific middleware per route or controller manually

In most PHP MVC frameworks, middleware is not called before the application instance is created. It is called after the application/bootstrap is initialized, but before the controller logic is executed.

🔍 Breakdown of Request Lifecycle in PHP MVC (e.g., Laravel, Symfony, Custom)

Let’s walk through the general flow:

  1. index.php (Front Controller) is hit first
    • This is the entry point for all requests.
    • It loads environment, autoloaders, and creates the application/kernel instance.
  2. Application/kernel is bootstrapped
    • At this stage, the core services (like routing, session, database) are initialized.
    • Then the request object is created and passed into the app.
  3. Middleware runs here (after app init, before routing/controller)
    • Global and route-specific middleware is executed.
    • Middleware can:
      • Modify the request/response
      • Short-circuit the request (e.g., return a 403)
      • Allow the request to continue to the controller
  4. Controller is resolved and executed
    • Only after middleware passes the request on.

⚙️ Example: Laravel Lifecycle

index.php
   ↓
bootstrap/app.php → creates the application instance
   ↓
App\Http\Kernel handles the request
   ↓
Middleware is applied (global first, then route-specific)
   ↓
Router finds and calls controller

So in Laravel and most modern PHP MVCs:

  • Application is initialized before middleware runs
  • Middleware does not run before the app instance is created

🛫 Analogy: Airport Security Checkpoint

Think of a Laravel request like a passenger trying to board a flight (reaching the controller/action).

And middleware is like the security checkpoints they pass through at the airport before boarding.


✈️ How it works:

  • 👤 Passenger (Request) arrives at the airport (your Laravel app).
  • 🔍 Middleware checks them:
    • Do they have a valid ID? (Are they authenticated?)
    • Do they have a boarding pass? (Do they have permission?)
    • Are they carrying anything dangerous? (Validate input, filter requests)
    • Are they wearing shoes? (Any extra condition you require)

If the passenger passes all checks, they are allowed to go to the gate (the controller).

If not, the middleware stops them and either redirects them, gives an error, or blocks them entirely.


🧱 Multiple Middleware = Multiple Checkpoints

Just like airports may have:

  • Passport control
  • Security scan
  • Boarding pass check

Laravel can have:

  • auth middleware (check if logged in)
  • verified middleware (check if email is verified)
  • admin middleware (check if user is admin)

Each middleware does one task, then passes the request to the next one.


🎯 Summary in One Line:

Middleware is like a checkpoint that processes or filters requests before they reach your main application logic (the controller).