Last active
July 13, 2026 19:47
-
-
Save vudaltsov/e70adba3062ddda593a68ff37fc4ae8b to your computer and use it in GitHub Desktop.
Middleware Pipeline Designs
This file contains hidden or 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); | |
| interface Context {} | |
| interface Handler | |
| { | |
| public function handle(object $message, Context $context): void; | |
| } | |
| interface Middleware | |
| { | |
| public function process(object $message, Context $context, Handler $next): void; | |
| } | |
| final class Pipeline implements Handler | |
| { | |
| private int $offset = 0; | |
| /** | |
| * @param non-empty-list<Middleware> $middlewareList | |
| */ | |
| public function __construct( | |
| private readonly Handler $handler, | |
| private readonly array $middlewareList, | |
| ) {} | |
| public function handle(object $message, Context $context): void | |
| { | |
| $middleware = $this->middlewareList[$this->offset] ?? null; | |
| if ($middleware === null) { | |
| $this->handler->handle($message, $context); | |
| return; | |
| } | |
| ++$this->offset; // мутация | |
| $middleware->process($message, $context, $this); | |
| } | |
| } |
This file contains hidden or 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 | |
| interface Context {} | |
| interface Handler | |
| { | |
| public function handle(object $message, Context $context): void; | |
| } | |
| interface Middleware | |
| { | |
| public function process(object $message, Context $context, Handler $next): void; | |
| } | |
| final readonly class MiddlewareHandler implements Handler | |
| { | |
| public function __construct( | |
| private Middleware $middleware, | |
| private Handler $handler, | |
| ) {} | |
| public function handle(object $message, Context $context): void | |
| { | |
| $this->middleware->process($message, $context, $this->handler); | |
| } | |
| } | |
| function stackMiddleware(Handler $handler, Middleware ...$middlewareList): Handler | |
| { | |
| foreach (array_reverse($middlewareList) as $middleware) { | |
| $handler = new MiddlewareHandler($middleware, $handler); | |
| } | |
| return $handler; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment