labrador-kennel / async-event
由 Amp Event Loop 驱动的语义应用事件触发器
v4.1.0
2024-05-31 15:11 UTC
Requires
- php: ^8.2
- amphp/amp: ~v3.0
- labrador-kennel/composite-future: ^1.2
Requires (Dev)
- amphp/phpunit-util: dev-phpunit-10-support
- cspray/labrador-coding-standard: 0.2.0
- mockery/mockery: ^1.6
- phpunit/phpunit: ^10
- psalm/phar: ^5.6
- roave/security-advisories: dev-latest
Suggests
- labrador-kennel/async-event-autowire: If using cspray/annotated-container will allow you to automatically register Listener implementations into your Emitter.
This package is auto-updated.
Last update: 2024-08-31 00:28:05 UTC
README
Labrador Async Event 提供了一种在 amphp/amp 事件循环上发出语义事件的方法。它提供了一套强大的功能,用于与事件系统一起工作,包括
- 使用
Labrador\AsyncEvent\Event
接口对事件的一级表示。 - 事件包括丰富的数据集;包括事件发出的日期和时间以及类型安全的对象有效载荷。
- 使用
Labrador\AsyncEvent\Listener
接口对事件监听器的一级表示。 - 使用面向对象的 API 移除监听器。
- 发出不阻塞当前执行的“发射并忘却”事件
安装
Composer 是安装 Labrador 包的唯一支持方法。
composer require labrador-kennel/async-event
使用指南
本指南详细说明了如何使用 Async Event v4+。这个版本做出了重大更改,并朝着类型安全、稳定的 API 发展。请查阅您所使用版本的 README 文件。
<?php declare(strict_types=1); namespace Labrador\AsyncEvent\Demo; use Amp\Future; use Labrador\AsyncEvent\AbstractEvent; use Labrador\AsyncEvent\Event; use Labrador\AsyncEvent\Listener; use Labrador\CompositeFuture\CompositeFuture; final class MyDomainObject {} /** * @extends AbstractEvent<MyDomainObject> */ final class MyDomainEvent extends AbstractEvent { public function __construct(MyDomainObject $object) { parent::__construct('my-domain-event', $object); } } /** * @implements Listener<MyDomainObject> */ final class MyListener implements Listener { public function handle(Event $event) : Future|CompositeFuture|null { return null; } }
现在,创建一个 EventEmitter 并注册您的监听器。然后发出一个事件!
<?php declare(strict_types=1); namespace Labrador\AsyncEvent\Demo; use Amp\CompositeException;use Labrador\AsyncEvent\AmpEmitter; $emitter = new AmpEmitter(); // You can remove the Listener later by calling $registration->remove() $registration = $emitter->register('my-domain-event', new MyListener()); $myDomainObject = new MyDomainObject(); // Emit an event and call an await method on the CompositeFuture returned $emitter->emit(new MyDomainEvent($myDomainObject))->await(); // Queue a fire & forget event, pass a callback to `finished()` if you want // to know when the listeners for queued event are finished $emitter->queue(new MyDomainEvent($myDomainObject)) ->finished( static fn(?CompositeException $exception, array $values) => doSomething() );