avris/dispatcher

事件分发器

v1.0.0 2017-12-31 12:11 UTC

This package is auto-updated.

Last update: 2024-08-29 05:11:57 UTC


README

安装

composer require avris/dispatcher

事件定义

事件是一个扩展 Avris\Dispatcher\Event 的对象。它必须提供其名称(用作触发它的标识符)以及其值的设置器和获取器(例如,如果 RequestEvent 应该产生一个 Response,那么响应就是值)。

例如

final class RequestEvent extends Event
{
    /** @var RequestInterface */
    private $request;

    /** @var ResponseInterface */
    private $response;

    public function __construct(RequestInterface $request)
    {
        $this->request = $request;
    }

    public function getName(): string
    {
        return 'request';
    }

    public function getRequest(): RequestInterface
    {
        return $this->request;
    }

    public function getResponse(): ?ResponseInterface
    {
        return $this->response;
    }

    public function setResponse(ResponseInterface $response): self
    {
        $this->response = $response;

        return $this;
    }

    public function setValue($value): Event
    {
        $this->response = $value;

        return $this;
    }

    public function getValue()
    {
        return $this->response;
    }
}

附加监听器

$dispatcher = new EventDispatcher();
$dispatcher->attachListener('request', function (RequestEvent $event) {
    if (substr($event->getRequest()->getUrl(), 0, 6) === '/admin' && !is_admin()) {
        return new Response('Forbidden', 403);
    }
});

返回任何非 null 的值将自动设置事件值(您也可以使用 $event->setResponse($response) 明确地设置它)。

attachListener 的最后一个参数中,您可以指定监听器的优先级,例如

$dispatcher->attachListener('request', [$this, 'one']);
$dispatcher->attachListener('request', [$this, 'two']);
$dispatcher->attachListener('request', [$this, 'three'], -9);
$dispatcher->attachListener('request', [$this, 'four'], 9);

监听器将按以下顺序触发: fouronetwothree

要停止事件传播,请使用 $event->stopPropagation()

触发事件

要触发事件

$response = $dispatcher->trigger(new RequestEvent($request));

如您所见,执行监听器后,事件的值将返回以方便使用(同样,您也可以明确使用 $event->getResponse())。

事件订阅者

订阅者是一个以优雅的方式定义事件监听器的对象,封装了与一个服务相关联的多个可能的监听器。

它需要实现 Avris\Dispatcher\EventSubscriberInterface

final class FooService implements EventSubscriberInterface
{
    public function getSubscribedEvents(): iterable
    {
        yield 'request' => [$this, 'onRequest'];
        yield 'response:9' => [$this, 'onResponse']; // priority 9
    }
}

要将它们注册到分发器中

$fooService = new FooService();
$this->dispatcher->registerSubscriber($fooService);

版权