Skip to content

事件配置 ​

概述 ​

事件模块的装配由 EventConfiguration 负责,它向容器注册三个服务(PSR-14 分发器、命名分发器、注册表),并在首次分发时从两个来源收集监听器:#[EventListener] 组件与 application.listeners 配置。

容器绑定 ​

容器服务 ID实现说明
Psr\EventDispatcher\EventDispatcherInterfaceLazyEventDispatcherPSR-14 分发器;首次 dispatch() 时才收集并注册监听器
kuiper\event\NamedEventDispatcherInterface与上面同一个实例仅是「按事件名分发」的静态类型视图,暴露成独立接口
kuiper\event\EventRegistryInterfaceEventDispatcher底层注册表(addListener() / reset())

自定义事件名分发器与 PSR-14 分发器是同一个实例——如果容器里的分发器不支持命名分发(被业务替换成仅实现 PSR-14 的实现类),获取 NamedEventDispatcherInterface 时会抛 RuntimeException。

此外,EventConfiguration 通过 addBeanAwareInjection() 注册了 EventDispatcherAwareInterface 的 setter 注入:监听器类实现该接口(配合 EventDispatcherAwareTrait),容器装配时自动注入分发器。

配置键 ​

配置键类型默认值说明
application.listenersarray[]监听器注册表,支持两种写法,见下文
application.bootstrap_listenersarray[]已废弃,application.listeners 的历史别名;非空时触发 E_USER_DEPRECATED

application.listeners ​

支持两种条目形态,可混合使用:

map 形式:事件名 => 监听器

php
<?php

declare(strict_types=1);

// src/config.php
return [
    'application' => [
        'listeners' => [
            // 键是事件名(通常是事件类名),值是容器服务 ID 或任意 callable
            App\Event\UserRegistered::class => App\Listener\SendWelcomeMail::class,
        ],
    ],
];

map 形式下事件名以配置键为准,监听器必须是 callable(容器解析出的服务对象可调用,或本身是 callable 服务)。监听器不需要实现 EventListenerInterface。

列表形式:监听器数组

php
<?php

declare(strict_types=1);

// src/config.php
return [
    'application' => [
        'listeners' => [
            App\Listener\SendWelcomeMail::class,   // 实现 EventListenerInterface
            App\Listener\AuditTrail::class,        // 实现 EventSubscriberInterface
        ],
    ],
];

列表形式下事件名由监听器自己声明:实现 EventListenerInterface 的监听单个事件(getSubscribedEvent()),实现 EventSubscriberInterface 的可订阅多个事件(getSubscribedEvents(),返回 string[])。

注册规则汇总 ​

EventConfiguration::resolveListenerRegistrations() 的完整判定顺序:

  1. 显式给出事件名(#[EventListener] 属性参数,或配置 map 的键):以事件名为准,监听器必须是 callable,否则跳过并记录 warning
  2. 实现 EventListenerInterface: 注册到 getSubscribedEvent() 返回的事件
  3. 实现 EventSubscriberInterface: 注册到 getSubscribedEvents() 返回的每个事件
  4. 都不命中: 跳过,记录 warning(不实现接口也不是 callable)

application.bootstrap_listeners(已废弃) ​

php
<?php

declare(strict_types=1);

// 旧写法,仍能用但会触发 E_USER_DEPRECATED
return [
    'application' => [
        'bootstrap_listeners' => [
            App\Event\UserRegistered::class => App\Listener\SendWelcomeMail::class,
        ],
    ],
];

语义与 application.listeners 完全相同(先于其注册),建议迁移到 application.listeners。

监听器的执行时机 ​

监听器不是在容器构建时注册的。v0.9 没有 Swoole server 启动事件,也没有容器 boot 阶段,监听器在第一次 dispatch() 时才注册(LazyEventDispatcher)。这意味着:

  • 监听器类可以放心在自己的构造函数里注入分发器(EventDispatcherAwareInterface 自动注入),不会循环依赖
  • 初始化失败后下次分发会自动重试,重试前先 reset() 清掉上次可能注册了一半的监听器
  • 注册过程使用的日志器优先取 LoggerFactoryInterface 按类名过滤级别,回退容器里的 LoggerInterface(日志模块)

相关页面 ​

  • 概述 - 分发器语义与监听器写法
  • 测试 - 事件测试替身与监听器测试

基于 MIT 许可发布