Psr7 Middleware queue and interface
, (*1)
, (*2)
Installation
> composer require lucid/infuse
Requirements
- php >= 5.6
- psr/http-message
- lucid/signal
Usage
The middleware
Middlewares must implement Lucid\Infuse\MiddlewareInterface
. They also must return
an array of [Psr\Http\Message\ServerRequestInterface $request, Psr\Http\Message\ResponseInterface $respoonse]
., (*3)
<?php
namespace Acme\Middleware;
use Lucid\Infuse\MiddlewareInterface;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
class SessoionHandler implements MiddlewareInterface
{
public function handle(Request $request, Response $response)
{
// ...
return [$request, $response];
}
}
The middleware queue
Use QueueInterface::add()
to add middlewares to the execution queue.
Middlewares are executed first in last out.
The middleware queue itself implements Lucid\Infuse\MiddlewareInterface
and
acts as an entrypoint., (*4)
<?php
use Lucid\Infuse\Queue;
use Lucid\Signale\EventDispatcher;
$queue = new Queue(new EventDispatcher);
$queue->add($middlewareOmega); // will execute last
// …
$queue->add($middlewareAlpha); // fill execute first
// …
list ($request, $response) = $queue->handle($request, $response);
Intercept execution
During middleware exection, the eventdispatcher will fire a request event.
Execution will stop if a middleware event is being stopped., (*5)
<?php
use Lucid\Infuse\Queue;
use Lucid\Signale\EventDispatcher;
use Lucid\Infuse\Events\RequestEvent;
$queue = new Queue($events = new EventDispatcher, 'middleware');
$events->addHandler('middleware', function (RequestEvent $event) {
$req = $event->getRequest();
$res = $event->getResponse();
if (…) {
$event->setResponse(…);
$event->stop();
}
});