a50 / event-dispatcher
事件调度器
dev-main
2024-05-10 04:23 UTC
Requires
- php: ^8.1
- a50/container: dev-main
- innmind/immutable: ^5.0
- psr/event-dispatcher: ^1.0
- webmozart/assert: ^1.11
This package is auto-updated.
Last update: 2024-09-10 05:09:44 UTC
README
A50 事件调度器
这是一个PSR-14事件调度器的简单实现,并且是一个与框架无关的解决方案。
为什么还要另一个呢?
因为
- 您想要遵循标准,而不用担心实现细节。您可以随时将此提供者更改为另一个提供者;
- 您不需要复杂且开销大的解决方案;
- 您希望轻松配置和使用事件调度器。
要求
- 最低PHP版本为8.0。
安装
您可以通过Composer安装此包
composer require a50/event-dispatcher
用法
以下是一个独立使用示例。在您的实体中,您需要注册事件
<?php declare(strict_types=1); namespace YourProject\Domain; use A50\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 A50\EventDispatcher\ImmutablePrioritizedListenerProvider; use A50\EventDispatcher\ListenerPriority; use A50\EventDispatcher\PrioritizedListenerProvider; use A50\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,您可以从 A50\EventDispatcher\EventDispatcherServiceProvider
类中获取定义。之后,在您的应用程序中,您可以轻松注入 Psr\EventDispatcher\EventDispatcherInterface
。
此外,您还可以为事件配置监听器,将它们传递到配置中
use A50\EventDispatcher\EventDispatcherConfig; use YourProject\Domain\UserWasRegistered; use YourProject\Application\SendEmailToModerator; $config = EventDispatcherConfig::withDefaults() ->addEventListener(UserWasRegistered::class, SendEmailToModerator::class) ->listeners();
甚至设置优先级(默认为 ListenerPriority::NORMAL
)
use A50\EventDispatcher\EventDispatcherConfig; use A50\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)。有关更多信息,请参阅许可证文件。