How do you create and use middleware in Slim Framework?

How do you create and use middleware in Slim Framework?

To create and use middleware in the Slim Framework, follow these minimal steps:

Steps to Create and Use Middleware in Slim Framework:

  1. Create Middleware Class: Define a class that will handle middleware logic using the __invoke() method, which accepts the request, response, and next middleware.

Example

<?php
namespace App\Middleware;

class ExampleMiddleware
{
    public function __invoke($request, $handler)
    {
        // Pre-processing logic before the route is handled
        $response = $handler->handle($request);
        
        // Post-processing logic after the route is handled
        $response->getBody()->write(' - Post-Middleware Logic');
        
        return $response;
    }
}
?>
  1. Add Middleware to Routes or Globally:
You can register middleware either globally (for all routes) or for specific routes. For Global Middleware:

Example

<?php
use App\Middleware\ExampleMiddleware;

$app->add(new ExampleMiddleware());
?>

For Specific Routes:

Example

<?php
$app->get('/hello', function ($request, $response, $args) {
    $response->getBody()->write("Hello, World!");
    return $response;
})->add(new ExampleMiddleware());
?>
  1. Run the Application:
After adding middleware to your routes or globally, run the Slim application.

Example

<?php
$app->run();
?>

How Middleware Works:

  • Pre-Processing: Logic before the request reaches the route (e.g., authentication, logging).
  • Post-Processing: Logic after the request has been handled (e.g., modifying response).

Example Flow:

When you visit a route with middleware added:

  1. Pre-process the request.
  2. Proceed to the route handler.
  3. Post-process the response.

This approach allows you to create reusable middleware for tasks like authentication, logging, or response modification.

Related Questions & Topics