lucid/infuse

psr7 middlware

Installs: 18

Dependents: 0

Suggesters: 0

Security: 0

Stars: 0

Watchers: 2

Forks: 0

Open Issues: 0

Type:package

v0.0.2 2016-04-21 18:27 UTC

This package is not auto-updated.

Last update: 2024-11-09 19:45:45 UTC


README

Author Source Code Software License

Build Status Code Coverage HHVM

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].

<?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.

<?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.

<?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();
    }
});