A middleware pipeline
Each middleware can act before and after the next one. The last step is your real handler.
PHP · A middleware pipelineAdvanced
function pipeline(array $middleware, callable $core): callable
{
$next = $core;
foreach (array_reverse($middleware) as $mw) {
$next = fn(array $req) => $mw($req, $next);
}
return $next;
}
$auth = function (array $req, callable $next) {
if (empty($req['user'])) {
return ['status' => 401, 'body' => 'Login required'];
}
return $next($req);
};
$timer = function (array $req, callable $next) {
$res = $next($req);
$res['headers']['X-Time'] = 'ok';
return $res;
};
$app = pipeline([$timer, $auth], fn(array $req) => ['status' => 200, 'body' => 'Hello ' . $req['user']]);
print_r($app(['user' => 'Ali']));
print_r($app([]));middlewarepipelineclosure