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:
// Intercepting an HTTP request -------------------
$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:
// Intercepting an HTTP response ----------------
$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;
};
// ----------------------------------------------

← Rendering Templates | Preparing New Project →