zorachka / event-dispatcher
事件分发器
v3.2.0
2023-09-25 05:44 UTC
Requires
- php: ^8.1
- psr/event-dispatcher: ^1.0
- webmozart/assert: ^1.11
- zorachka/container: ^3.1
README
Zorachka 事件分发器
这是PSR-14事件分发器的简单实现和框架无关的解决方案。
为什么还要另一个呢?
因为
- 你希望遵循标准并且不必担心实现。你可以随时将此提供程序更改为另一个程序;
- 你不需要复杂且开销大的解决方案;
- 你想要轻松配置和使用事件分发器。
要求
- 最低PHP版本是8.0。
安装
你可以通过composer安装此包
composer require zorachka/event-dispatcher
用法
以下为独立使用示例。在你的实体中,你需要注册事件
<?php declare(strict_types=1); namespace YourProject\Domain; use Zorachka\EventDispatcher\EventRecordingCapabilities; final class Post { use EventRecordingCapabilities; // use trait to register and release events private function __construct(private PostId $id) { } public static function create(PostId $id): self { $self = new self($id); $self->registerThat(PostWasCreated::withId($id)); // register event return $self; } }
配置Psr\EventDispatcher\EventDispatcherInterface
<?php declare(strict_types=1); require __DIR__ . 'vendor/autoload.php'; use Zorachka\EventDispatcher\ImmutablePrioritizedListenerProvider; use Zorachka\EventDispatcher\ListenerPriority; use Zorachka\EventDispatcher\PrioritizedListenerProvider; use Zorachka\EventDispatcher\SyncEventDispatcher; use YourProject\Domain\Post; use YourProject\Domain\PostId; use YourProject\Domain\PostWasCreated; use YourProject\Application\SendEmailToModerator; use YourProject\Domain\UserWasRegistered; use YourProject\Application\SendWelcomeEmail; $registry = new ImmutablePrioritizedListenerProvider([ new PrioritizedListenerProvider(PostWasCreated::class, [ ListenerPriority::NORMAL => new SendEmailToModerator(), ]), new PrioritizedListenerProvider(UserWasRegistered::class, [ ListenerPriority::NORMAL => new SendWelcomeEmail(), ]), ]); $dispatcher = new SyncEventDispatcher($registry); // And in your application use case: $post = Post::create( PostId::fromString('00000000-0000-0000-0000-000000000000') ); foreach ($post->releaseEvents() as $event) { $dispatcher->dispatch($event); }
当然,最好是使用DI,你可以从Zorachka\EventDispatcher\EventDispatcherServiceProvider类中获取定义。之后,在你的应用程序中,你可以轻松地注入Psr\EventDispatcher\EventDispatcherInterface。
此外,你可以为事件配置监听器,将它们传递到配置中
use Zorachka\EventDispatcher\EventDispatcherConfig; use YourProject\Domain\UserWasRegistered; use YourProject\Application\SendEmailToModerator; $config = EventDispatcherConfig::withDefaults() ->addEventListener(UserWasRegistered::class, SendEmailToModerator::class) ->listeners();
并且甚至设置优先级(默认为ListenerPriority::NORMAL)
use Zorachka\EventDispatcher\EventDispatcherConfig; use Zorachka\EventDispatcher\ListenerPriority; use YourProject\Application\SendEmailToModerator; use YourProject\Domain\UserWasRegistered; $config = EventDispatcherConfig::withDefaults() ->addEventListener(UserWasRegistered::class, SendEmailToModerator::class, ListenerPriority::HIGH) ->listeners();
测试
make test
变更日志
请参阅变更日志以获取有关最近更改的更多信息。
贡献
请参阅贡献指南以获取详细信息。
安全漏洞
请参阅我们的安全策略了解如何报告安全漏洞。
鸣谢
许可协议
MIT许可协议(MIT)。请参阅许可文件以获取更多信息。