neat / event
Neat Event 组件
0.1.4
2023-02-02 10:47 UTC
Requires
- php: >=7.2
- neat/service: ^0.3.2
- psr/event-dispatcher: ^1.0
- psr/log: ^1.1
Requires (Dev)
- phpunit/phpunit: ^8.0 || ^9.0
Provides
README
Neat Event 组件为您的应用程序提供了一个干净且易于表达的事件分发和监听API。Neat Event 组件实现了 PSR-14 接口,以实现最佳互操作性。
注意:事件监听器必须将第一个参数命名为 '$event'。
入门指南
要安装此包,只需在命令行中运行 composer
composer require neat/event
事件调度器可以通过几行代码创建。
<?php // First create your container (used for event dispatching and dependency injection) $container = new Neat\Service\Container(); // The dispatcher will need a service container for dependency injection $dispatcher = new Neat\Event\Dispatcher($container);
定义事件
<?php // A generic event can be defined using a simple PHP class without any members class SomeEvent { } // Specific events may also use inheritance using extends or interfaces class SomeSpecificEvent extends SomeEvent { } // Implement the Stoppable event interface if you want control over dispatching your event class SomeStoppableEvent implements Neat\Event\Stoppable { public function isPropagationStopped(): bool { return random_int(0, 1) == 1; } }
监听事件
您的监听器可以是任何可调用的函数或方法,只要它有一个 $event
参数,用于接受我们正在监听的事件对象。
<?php // Now listen for events of this class or any of its subclasses or implementations $dispatcher->listen(SomeEvent::class, function (SomeEvent $event) { // ... }); // Or for a specific event $dispatcher->listen(SomeSpecificEvent::class, function (SomeSpecificEvent $event) { // ... });
分发事件
现在我们准备好分发事件了。
<?php // This will trigger only the SomeEvent listener, NOT the SomeSpecificEvent listener $dispatcher->dispatch(new SomeEvent()); // This will trigger both the SomeEvent and SomeSpecificEvent listeners $dispatcher->dispatch(new SomeSpecificEvent());