事件模块
Kuiper 框架的事件模块提供一个基于 PSR-14 的事件分发器,并在其上扩展了自定义事件名分发、监听器自动注册与惰性初始化。事件监听器同样以「组件」的形式写在业务代码里,由组件扫描自动发现。
特性
- PSR-14 标准: 分发器实现
Psr\EventDispatcher\EventDispatcherInterface,可替换、可组合 - 属性驱动注册: 监听器类标上
#[EventListener]即被组件扫描发现,自动注册 - 配置注册: 支持
application.listeners配置,把任意 callable 或服务注册为监听器 - 精确事件名匹配: 事件名默认取事件的精确类名,不做父类/接口兜底,行为可预期
- 惰性初始化: 监听器在第一次
dispatch()时才注册,避免容器构建期的循环依赖 - 自定义事件名: 同一个事件对象可以按不同的事件名分发(
dispatchNamed()) - 可停止传播:
StoppableEventTrait让任意事件类支持中断后续监听器
快速开始
监听 PSR-14 事件
最简单的写法:定义事件类(普通对象即可),监听器实现 EventListenerInterface 并标上 #[EventListener]:
<?php
declare(strict_types=1);
namespace App\Event;
class UserRegistered
{
public function __construct(
public readonly string $userId
) {
}
}<?php
declare(strict_types=1);
namespace App\Listener;
use App\Event\UserRegistered;
use kuiper\event\EventListenerInterface;
use kuiper\event\attribute\EventListener;
#[EventListener]
class SendWelcomeMail implements EventListenerInterface
{
public function __invoke(object $event): void
{
assert($event instanceof UserRegistered);
// 发送欢迎邮件
}
public function getSubscribedEvent(): string
{
return UserRegistered::class;
}
}getSubscribedEvent() 返回的事件名就是分发时的事件名(默认是事件的类名)。
分发事件
在业务代码里注入 PSR-14 分发器接口,调用 dispatch():
<?php
declare(strict_types=1);
namespace App\Service;
use App\Event\UserRegistered;
use Psr\EventDispatcher\EventDispatcherInterface;
class UserService
{
public function __construct(
private readonly EventDispatcherInterface $eventDispatcher
) {
}
public function register(string $userId): void
{
// ... 注册逻辑
$this->eventDispatcher->dispatch(new UserRegistered($userId));
}
}容器里的绑定关系:
| 容器服务 ID | 实现 | 说明 |
|---|---|---|
Psr\EventDispatcher\EventDispatcherInterface | LazyEventDispatcher | PSR-14 分发器,首次分发时初始化 |
kuiper\event\NamedEventDispatcherInterface | 同一个 LazyEventDispatcher | 「按事件名分发」的静态类型视图 |
kuiper\event\EventRegistryInterface | EventDispatcher | 底层注册表,管理监听器 |
监听一个事件类的多种语义(自定义事件名)
PSR-14 的 dispatch() 没有事件名参数。需要把同一个事件对象按自定义事件名分发时,注入 NamedEventDispatcherInterface:
<?php
declare(strict_types=1);
use kuiper\event\NamedEventDispatcherInterface;
final class AuditLogger
{
public function __construct(
private readonly NamedEventDispatcherInterface $dispatcher
) {
}
public function onUserAction(object $action): void
{
// 监听器可以按 'audit.action' 注册,而不是按事件类名
$this->dispatcher->dispatchNamed($action, 'audit.action');
}
}核心语义
事件名是精确类名匹配
dispatch() 不传事件名时,事件名取 $event::class 的精确类名——不做父类、接口的兜底匹配。监听器注册到什么事件名,就只能收到什么事件名分发的事件:
// 监听器注册到 UserRegistered::class
// dispatch(new UserRegistered('u1')) → 收到
// dispatch(new AdminRegistered('a1')) → 收不到,即使 AdminRegistered extends UserRegistered按自定义事件名 dispatchNamed() 分发只影响本次分发的事件名,类名精确匹配的语义不变。
传播停止
事件实现 PSR-14 的 StoppableEventInterface,或者直接 use StoppableEventTrait,监听器里调用 stopPropagation() 后,排在其后的监听器不再执行:
<?php
declare(strict_types=1);
namespace App\Event;
use kuiper\event\StoppableEventTrait;
class Notification
{
use StoppableEventTrait;
public function __construct(
public readonly string $channel
) {
}
}kuiper\event\EventDispatcher 自己遍历监听器而不是直接委托 Symfony 的 dispatch(),因为 Symfony 只认 StoppableEventInterface——仅 use 了 StoppableEventTrait(无法自动实现接口)的事件也要能中断传播。
惰性初始化与 reset 兜底
v0.9 的容器没有 boot 阶段,监听器注册被推迟到第一次 dispatch()(LazyEventDispatcher):
- 首次分发时执行初始化:清空注册表(
reset())后重新收集所有监听器 - 初始化进行中再次触发
dispatch()不会重复注册(initializing防重入) - 初始化失败(例如某个监听器的依赖缺失)时保持未初始化状态,下次
dispatch()会重试;重试前先reset()清掉上次可能注册了一半的监听器,避免重复
这个设计让监听器可以在自己的构造/注入过程中安全地获取分发器(实现 EventDispatcherAwareInterface,框架自动 setter 注入),不会形成硬循环依赖。
监听器的四种注册方式
| 方式 | 写法 | 事件名来源 |
|---|---|---|
#[EventListener] 组件(无参) | 类标 #[EventListener],实现 EventListenerInterface | getSubscribedEvent() 返回值 |
#[EventListener] 组件(带事件名) | 类标 #[EventListener(UserRegistered::class)],监听器须为 callable | 属性参数 |
EventListenerInterface | 实现接口(可再标 #[EventListener] 让扫描收录) | getSubscribedEvent() |
application.listeners 配置 | 事件名 => callable 服务,或监听器列表 | map 键,或 getSubscribedEvent() / getSubscribedEvents() |
支持订阅多个事件的监听器实现 EventSubscriberInterface(注意方法名是复数的 getSubscribedEvents(),返回 string[])。
无法注册的监听器(四种规则都不命中)不会静默丢弃:框架记录 warning 日志说明跳过原因(不实现两个接口也不是 callable),缺日志器时写到 error_log。
已废弃的写法
kuiper\event\attribute\Async: v0.9 起异步事件体系已移除,该标记属性不再被任何代码读取kuiper\event\AsyncEventDispatcherInterface: 已废弃,容器不再绑定,请改用同步dispatch()
架构概览
流程说明:
- 首次分发触发注册:
LazyEventDispatcher在第一次dispatch()时从组件集合与配置收集监听器 - 委托存储:
EventDispatcher内部用 Symfony EventDispatcher 管理监听器的优先级与查找,但分发由自己控制 - 顺序执行: 按 Symfony 的优先级顺序调用监听器,任何监听器停止传播后中断
与可观测性的集成
kuiper\event\TelemetryFlushable 是一个标记接口,表示「这是一个适合冲刷 telemetry 的边界」:
- runtime 模块 的
RequestFinished事件实现了该接口 - otel 模块 的
FlushTelemetryOnRequest监听器按该接口订阅
其他形态的处理单元(如消息队列消费者处理完一条消息)也可以让自己的「处理完成」事件实现该接口,加入同一套冲刷机制——新增事件类型无需修改冲刷监听器。
测试替身
InMemoryEventDispatcher: 只记录被分发的事件、不执行任何监听器,用于断言「某个事件是否被分发、分发了几次」,详见测试NullEventDispatcher: 空实现,addListener()什么都不做,用于需要注册表的场景
文档导航
相关资源
- PSR-14: Event Dispatcher
- 依赖注入模块 - 组件扫描的工作方式