-
Notifications
You must be signed in to change notification settings - Fork 4
Creating Middlewares
Rougin Gutib edited this page Aug 10, 2024
·
9 revisions
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;
};
// ----------------------------------------------