tobento/service-event

支持自动装配的事件派发器。

1.0.1 2021-12-23 16:21 UTC

This package is auto-updated.

Last update: 2024-09-23 22:12:39 UTC


README

支持自动装配的事件派发器。

目录

入门指南

运行以下命令添加运行此命令的事件服务最新版本。

composer require tobento/service-event

需求

  • PHP 8.0 或更高版本

亮点

  • 框架无关,适用于任何项目
  • 解耦设计
  • 支持自动装配

简单示例

以下是一个如何使用事件服务的简单示例。

use Tobento\Service\Event\Dispatcher;
use Tobento\Service\Event\Listeners;

class FooEvent {}

$listeners = new Listeners();

$listeners->add(function(FooEvent $event) {
    // do something
});

$dispatcher = new Dispatcher($listeners);

$event = $dispatcher->dispatch(new FooEvent());

使用事件

use Tobento\Service\Event\Events;

class FooEvent {}

$events = new Events();

$events->listen(function(FooEvent $event) {
    // do something
});

$event = $events->dispatch(new FooEvent());

文档

监听器

监听器类使用反射来扫描监听器的事件。

创建监听器

use Tobento\Service\Event\Listeners;
use Tobento\Service\Event\ListenersInterface;
use Tobento\Service\Event\CallableFactoryInterface;
use Tobento\Service\Event\ListenerEventsResolverInterface;
use Psr\EventDispatcher\ListenerProviderInterface;
    
$listeners = new Listeners(
    callableFactory: null, // null|CallableFactoryInterface
    listenerEventsResolver: null, // null|ListenerEventsResolverInterface
);

var_dump($listeners instanceof ListenersInterface);
// bool(true)

var_dump($listeners instanceof ListenerProviderInterface);
// bool(true)

使用自动装配

您可能想使用自动装配来创建监听器。

use Tobento\Service\Event\Listeners;
use Tobento\Service\Event\AutowiringCallableFactory;
use Tobento\Service\Container\Container;

class FooListener
{
    public function foo(FooEvent $event): void
    {
        // do something
    }
}

// any PSR-11 container
$container = new Container();
    
$listeners = new Listeners(
    callableFactory: new AutowiringCallableFactory($container),
);

$listeners->add(FooListener::class);

定义并添加监听器

由于监听器类使用反射来扫描名为 $event 的事件,因此添加监听器时无需定义其事件。但如果您的监听器中有多个事件,并且只想监听特定事件,则可以定义事件。

使用 invoke 的类

class FooListener
{
    public function __invoke(FooEvent $event): void
    {
        // do something
    }
}

class FooBuildInListener
{
    public function __construct(protected int $number) {}
    
    public function __invoke(FooEvent $event): void
    {
        // do something
    }
}

$listeners->add(new FooListener());

// using autowiring:
$listeners->add(FooListener::class);

// using autowiring with build-in parameters:
$listeners->add([FooBuildInListener::class, ['number' => 5]]);

定义多个要监听的事件的类

class FooBarListener
{
    public function foo(FooEvent $event): void
    {
        // do something
    }
    
    public function bar(BarEvent $event): void
    {
        // do something
    }
    
    public function another(AnotherEvent $event): void
    {
        // do something
    }    
    
    public function fooAndBar(FooEvent|BarEvent $event): void
    {
        // do something
    }    
}

// only listen to foo and bar event: 
$listeners->add(new FooBarListener())
          ->event(FooEvent::class, BarEvent::class);
          
// using autowiring:
$listeners->add(FooBarListener::class)
          ->event(FooEvent::class, BarEvent::class);

使用闭包

$listeners->add(function(FooEvent $event) {
    // do something
});

优先级

您可以通过以下方式对监听器进行优先级排序

$listeners->add(function(FooEvent $event) {
    // do something
})->priority(1500);

// gets called first as higher priority.
$listeners->add(function(FooEvent $event) {
    // do something
})->priority(2000);

添加自定义监听器

您可以通过实现以下接口来添加自定义监听器

use Tobento\Service\Event\ListenerInterface;
use Tobento\Service\Event\CallableFactoryInterface;

interface ListenerInterface
{
    /**
     * Returns the listener.
     *    
     * @return mixed
     */
    public function getListener(): mixed;

    /**
     * Returns the listener events.
     *    
     * @return array<string, array<mixed>>
     */
    public function getListenerEvents(): array;
    
    /**
     * Returns the listeners for the specified event.
     *
     * @param object $event
     * @param CallableFactoryInterface $callableFactory
     * @return iterable<callable>
     *   An iterable (array, iterator, or generator) of callables. Each
     *   callable MUST be type-compatible with $event.
     */
    public function getForEvent(object $event, CallableFactoryInterface $callableFactory): iterable;
    
    /**
     * Returns the priority.
     *    
     * @return int
     */
    public function getPriority(): int;   
}

$listeners->addListener(new AnyCustomListener());

检索监听器

use Tobento\Service\Event\ListenerInterface;

foreach($listeners->all() as $listener) {
    var_dump($listener instanceof ListenerInterface);
    // bool(true)
}

派发器

创建派发器

use Tobento\Service\Event\Dispatcher;
use Psr\EventDispatcher\EventDispatcherInterface;
use Psr\EventDispatcher\ListenerProviderInterface;
use Psr\Container\ContainerInterface;
use Tobento\Service\Event\Listeners;

$listeners = new Listeners();

$dispatcher = new Dispatcher(
    listenerProvider: $listeners, // ListenerProviderInterface
    container: null, // null|ContainerInterface
);

var_dump($dispatcher instanceof EventDispatcherInterface);
// bool(true)

使用自动装配

您可以为自动装配事件方法设置容器。但这将破坏 PSR-14 定义。

use Tobento\Service\Event\Dispatcher;
use Tobento\Service\Event\Listeners;
use Tobento\Service\Container\Container;

class FooEvent {}
class Bar {}

$listeners = new Listeners();

// adding more parameters after the $event.
$listeners->add(function(FooEvent $event, Bar $bar) {
    // do something
});

// Any PSR-11 container
$container = new Container();

$dispatcher = new Dispatcher(
    listenerProvider: $listeners,
    container: $container,
);

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

派发事件

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

事件

创建事件

use Tobento\Service\Event\Events;
use Tobento\Service\Event\EventsInterface;
use Tobento\Service\Event\ListenersInterface;
use Tobento\Service\Event\DispatcherFactoryInterface;
use Psr\EventDispatcher\EventDispatcherInterface;

$events = new Events(
    listeners: null, // null|ListenersInterface
    dispatcherFactory: null, // null|DispatcherFactoryInterface
);

var_dump($events instanceof EventsInterface);
// bool(true)

var_dump($events instanceof EventDispatcherInterface);
// bool(true)

使用事件工厂

use Tobento\Service\Event\EventsFactory;
use Tobento\Service\Event\EventsFactoryInterface;
use Tobento\Service\Event\ListenersInterface;
use Tobento\Service\Event\DispatcherFactoryInterface;
use Tobento\Service\Event\EventsInterface;

$eventsFactory = new EventsFactory();

var_dump($eventsFactory instanceof EventsFactoryInterface);
// bool(true)

$events = $eventsFactory->createEvents(
    listeners: null, // null|ListenersInterface
    dispatcherFactory: null, // null|DispatcherFactoryInterface
);

var_dump($events instanceof EventsInterface);
// bool(true)

使用自动装配事件工厂

use Tobento\Service\Event\AutowiringEventsFactory;
use Tobento\Service\Event\EventsFactoryInterface;
use Tobento\Service\Event\EventsInterface;
use Tobento\Service\Container\Container;

// Any PSR-11 container
$container = new Container();

$eventsFactory = new AutowiringEventsFactory(
    container: $container,
    withAutowiringDispatching: true,
);

var_dump($eventsFactory instanceof EventsFactoryInterface);
// bool(true)

$events = $eventsFactory->createEvents();

var_dump($events instanceof EventsInterface);
// bool(true)

添加监听器

使用 listen 方法

$events->listen(FooListener::class);

$events->listen(AnyListener::class)
       ->event(FooEvent::class)
       ->priority(2000);

使用 listeners 方法

use Tobento\Service\Event\ListenersInterface;

$listeners = $events->listeners();

var_dump($listeners instanceof ListenersInterface);
// bool(true)

$listeners->add(AnyListener::class);

有关更多详细信息,请参阅 定义并添加监听器

派发事件

$events->dispatch(new AnyEvent());

支持的事件

您可以使用具有 EventsAware 接口的 HasEvents 特性来为任何支持事件的类。

use Tobento\Service\Event\EventsAware;
use Tobento\Service\Event\HasEvents;
use Tobento\Service\Event\EventsInterface;
use Tobento\Service\Event\Events;

class AnyService implements EventsAware
{
    use HasEvents;
    
    public function __construct(EventsInterface $events)
    {
        $this->events = $events;
    }
}

$service = new AnyService(new Events());

var_dump($service->events() instanceof EventsInterface);
// bool(true)

鸣谢