Last active
September 7, 2021 18:28
-
-
Save Nyholm/a7166e6e570738bee75612c3608aa4e3 to your computer and use it in GitHub Desktop.
A simple middleware runner for PSR7
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types=1); | |
namespace App; | |
use Psr\Http\Message\ResponseInterface; | |
use Psr\Http\Message\ServerRequestInterface; | |
class Runner | |
{ | |
/** @var callable[] */ | |
private $queue; | |
public function __construct(array $queue) | |
{ | |
$this->queue = $queue; | |
} | |
public function __invoke(ServerRequestInterface $request, ResponseInterface $response) | |
{ | |
$middleware = array_shift($this->queue); | |
if (null === $middleware) { | |
// Default | |
return function (ServerRequestInterface $request, ResponseInterface $response, callable $next) { | |
return $response; | |
}; | |
} | |
return $middleware($request, $response, $this); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello! I am learning this middleware thing and while I was researching how to create middleware runner I found this gist. I tried to recreate it another way. Could you comment on that?
https://gist.github.com/mkoske/7a179a28a13d330829c4ed25abc6b303