getting started  »  middleware

Middleware

The middleware manager provides a way to hook specific functionality in and around the `dispatch` action in an application object. Middleware themselves are classes that would implement the following interfaces:

  • Pop\Middleware\MiddlewareInterface - required, defines the handle() method that will be called to execute the middleware
  • Pop\Middleware\TerminableInterface - optional, defines the terminate() method that can be called to execute any post-dispatch code
class TestMiddleware implements MiddlewareInterface, TerminableInterface
{

    public function handle(mixed $request, \Closure $next): mixed
    {
        echo 'Entering Test Middleware.
'; $response = $next($request); echo 'Exiting Test Middleware.
'; return $response; } public function terminate(mixed $request = null, mixed $response = null): void { file_put_contents( __DIR__ . '/logs/mw.log', 'Executing terminate method for test middleware.' . PHP_EOL, FILE_APPEND ); } }

Middleware can be added directly to the application object:

$app = new Pop\Application();
$app->middleware->addHandler('TestMiddleware');

Or via the application config:

$config = [
    'middleware' => ['TestMiddleware'],
    'routes'     => [
        '/' => [
            'controller' => function() {
                echo 'Index Page.
'; } ], ] ] $app = new Pop\Application($config); $app->run();

When making the request to the above application (e.g., http://localhost:8000/), the response will be:

Entering Test Middleware.
Index page.
Exiting Test Middleware.

Furthermore, the terminate() method will have been executed post-dispatch and added the following entry to the logs/mw.log log file:

Executing terminate method for test middleware.

Routes

Middleware can be applied globally or on a specific route-level. Middleware assigned to a specific route will only execute on that route.

$config = [
    'middleware' => ['TestMiddleware'],
    'routes'     => [
        '/' => [
            'controller' => function() {
                echo 'Index Page.
'; } ], '/admin[/]' => [ 'middleware' => 'AdminMiddleware', 'controller' => function() { echo 'Admin Page.
'; } ], ] ] $app = new Pop\Application($config); $app->run();