Skip to content

Creating Middlewares

Rougin Gutib edited this page Aug 10, 2024 · 9 revisions

← Rendering Templates | Preparing New Project →

What is a Middleware?

A Middleware is a layer of actions that are wrapped around a piece of core logic in an application. It provides functionality to change an HTTP request or an HTTP response. From the perspective of Slytherin, a middleware may do the following:

  • Intercept the incoming HTTP request and add additional payload prior going to the HTTP route:
$fn = function ($request, $next)
{
    // Modify the query parameters from request ---
    $data = array('name' => 'Slytherin');

    $request = $request->withQueryParams($data);
    // --------------------------------------------

    // Proceed to the next middleware ---
    return $next($request);
    // ----------------------------------
};
  • Or intercept the outgoing HTTP response then check if it is okay to be returned to the user:
$fn = function ($request, $next)
{
    // Returns the last middleware prior this ---
    $response = $next($request);
    // ------------------------------------------

    // Modify the response directly ------
    if ($response->getStatusCode() >= 500)
    {
        // Add sample conditions
    }
    // -----------------------------------

    return $response;
};

Implementing a Middleware

Prior to creating and adding middlewares to HTTP routes, a middleware dispatcher must be added first to the Container class:

// app/web/index.php

// ...

use Rougin\Slytherin\Middleware\Dispatcher;
use Rougin\Slytherin\Middleware\DispatcherInterface;

// ...

// Add the Middleware Dispatcher to the container ----------
$container->set(DispatcherInterface::class, new Dispatcher);
// ---------------------------------------------------------

After defining the middleware dispatcher, a middleware can be added into a HTTP route by adding it after the route action parameter:

// app/web/index.php

// ...

$middleware = function ($request, $next)
{
    $newQuery = array('name' => 'middleware');

    $request = $request->withQueryParams($newQuery);

    return $next->handle($request);
};

$app->get('/hello', function (ServerRequestInterface $request)
{
    $query = $request->getQueryParams();

    return 'Hello ' . ($query['name'] ?? 'world') . '!';
}, $middleware);

// ...

Opening the link below in a web browser should return a text of Hello middleware! even though there is a defined name query parameter since the HTTP request is was intercepted inside a middleware:

http://localhost:8000/hello

← Rendering Templates | Preparing New Project →