aatis / event-dispatcher
本包最新版本(1.0.0)没有可用的许可证信息。
Aatis的事件分发器
1.0.0
2024-02-14 14:15 UTC
Requires
- php: >=8.2
- aatis/dependency-injection: ^1.5
- psr/event-dispatcher: ^1.0
This package is auto-updated.
Last update: 2024-09-14 15:29:02 UTC
README
广告
此包是Aatis
的一部分,不能在没有以下包的情况下使用:
aatis/dependency-injection
(https://github.com/BatMaxou/aatis-DI)
安装
composer require aatis/event-dispatcher
使用
需求
将EventDispatcher
服务添加到Container
# In config/services.yaml file : include_services: - 'Aatis\EventDispatcher\Service\EventDispatcher'
事件
本包提供了一个可扩展的抽象Event
类,可以扩展以创建以下自定义事件
use Aatis\EventDispatcher\Event\Event; class ExampleEvent extends Event { }
可停止事件
本包还提供了一个可扩展的抽象StoppableEvent
类,可以扩展以创建以下自定义可停止事件
use Aatis\EventDispatcher\Event\StoppableEvent; class ExampleStoppableEvent extends StoppableEvent { }
此类实现了自定义的StoppableEventInterface
,它扩展了Psr\EventDispatcher\StoppableEventInterface
。
因此,使用此类,您可以访问以下两个特定方法
isPropagationStopped
,它返回一个布尔值,表示事件传播是否已停止stopPropagation
,它将传播设置为false
,必须在监听器或订阅者方法中调用
优先级
EventDispatcher
服务可以使用整数优先级量分发事件。优先级越高,事件越早分发。
如果有两个监听器对同一事件的优先级相同,这两个监听器的执行顺序是随机的。
默认情况下,优先级设置为0
。
事件监听器
监听器是一个类,可以在分发事件时调用。它必须包含一个__invoke
方法,该方法只有一个参数,该参数必须是监听的事件。
针对ExampleEvent
的监听器示例
class ExampleListener { public function __invoke(ExampleEvent $event): void { // Do something } }
您可以通过在类中附加带有priority
参数的EventListener
属性来指定监听器的优先级
#[EventListener(priority: 2)] class ExampleListener { public function __invoke(ExampleEvent $event): void { // Do something } }
最后,您必须通过向服务中添加event-listener
标签来通知容器此类是一个监听器
# In config/services.yaml file : services: App\Listener\ExampleListener: tags: - 'event-listener'
事件订阅者
订阅者是一个包含多个监听器方法和订阅多个事件的类。
它必须提供一个getSubscribedEvents
方法,该方法返回服务订阅的事件数组及其关联的监听器方法。
订阅者示例
class TestSubscriber implements EventSubscriberInterface { public function onExample(Event $event): void { // Do something } public function onExampleBis(Event $event): void { // Do something } public function getSubscribedEvents(): iterable { return [ ExampleEvent::class => 'onExample', ExampleBisEvent::class => 'onExampleBis', ]; } }
您也可以通过传递数组来为同一事件指定多个监听器
public function getSubscribedEvents(): iterable { return [ ExampleEvent::class => [ 'onExample', 'onExampleBis' ], ExampleBisEvent::class => 'onExampleBis', ]; }
对于优先级,您也可以传递包含监听器方法和优先级整数的数组
public function getSubscribedEvents(): iterable { return [ ExampleEvent::class => [ ['onExample', 2], 'onExampleBis' ], ExampleBisEvent::class => ['onExampleBis', 2], ]; }