How do you implement custom middleware in Slim Framework?

How do you implement custom middleware in Slim Framework?

To implement custom middleware in the Slim Framework, follow these steps:

Steps to Implement Custom Middleware in Slim:

  1. Create Middleware Class: Define a class that implements the middleware logic. Middleware classes should implement __invoke() to handle requests and responses.

Example

<?php
namespace App\Middleware;

class CustomMiddleware
{
    public function __invoke($request, $response, $next)
    {
        // Pre-processing: Before passing the request to the next middleware or route
        $response->getBody()->write('Before middleware logic ');

        // Proceed to the next middleware
        $response = $next($request, $response);

        // Post-processing: After passing the request to the next middleware or route
        $response->getBody()->write(' After middleware logic');

        return $response;
    }
}
?>
  1. Register Middleware in the Application:
Add the middleware to the Slim app, either globally (for all routes) or for specific routes.

Example

<?php
use App\Middleware\CustomMiddleware;

// Add middleware globally
$app->add(new CustomMiddleware());

// Or add middleware to a specific route
$app->get('/example', function ($request, $response, $args) {
    $response->getBody()->write('Hello from the route!');
    return $response;
})->add(new CustomMiddleware());
?>
  1. Run the Application:
Start the Slim app to see the middleware in action.

Example

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

Related Questions & Topics