circli/event-dispatcher

PSR-14 事件分发器实现。

3.0.0 2023-10-24 11:52 UTC

This package is auto-updated.

Last update: 2024-08-24 13:54:24 UTC


README

Latest Version on Packagist Software License Build Status Coverage Status

该包提供了一个标准的事件分发器,以及一个可以为默认分发器使用的空分发器,在 EventDispatcherAwareInterface 中使用。

安装

通过 Composer

$ composer require circli/event-dispatcher

使用方法

分发器在其构造函数中接受一个 Psr\EventDispatcher\ListenerProviderInterface

基本示例

use Circli\EventDispatcher\EventDispatcher;
use Circli\EventDispatcher\ListenerProvider\DefaultProvider;

$provider = new DefaultProvider();
$dispatcher = new EventDispatcher($provider);

$provider->listen(Event::class, function(Event $e) {
    // do stuff
});

$dispatcher->dispatch(new Event());

提供者

该包包含了一些易于使用的提供者。你还可以在 fig/event-dispatcher-util 中找到一些有用的提供者。

默认提供者

use Circli\EventDispatcher\ListenerProvider\DefaultProvider;
$provider = new DefaultProvider();
$provider->listen(Event::class, $listener);

优先级提供者

use Circli\EventDispatcher\ListenerProvider\PriorityProvider;
$provider = new PriorityProvider();

//Add listener with lower than default priority
$provider->listen(Event::class, $listener, 900);

//Add listener with higher than default priority
$provider->listen(Event::class, $listener, 1100);

//Add listener with normal priority
$provider->listen(Event::class, $listener);

容器监听器提供者

使用 Psr-11 容器来懒加载回调。

use Circli\EventDispatcher\ListenerProvider\ContainerListenerProvider;
$container = new SomePsr11Container();

$provider = new ContainerListenerProvider($container);
$provider->addService(Event::class, EventListener::class);

优先级聚合提供者

use Circli\EventDispatcher\ListenerProvider\PriorityAggregateProvider;
use Circli\EventDispatcher\ListenerProvider\DefaultProvider;

$aggregateProvider = new PriorityAggregateProvider();
$aggregateProvider->addProvider(new DefaultProvider());

// Add with higher than default priority
$aggregateProvider->addProviderWithPriority(new DefaultProvider(), 1500);

// Add with lower than default priority
$aggregateProvider->addProviderWithPriority(new DefaultProvider(), 500);

可筛选提供者

use Circli\EventDispatcher\ListenerProvider\FilterableProvider;

$provider = new FilterableProvider();

$provider->listen(RandomEvent::class, $listener, function ($event) {
    return ifRandomExternalThingIsTrue();
});