yii 3.0 中实现松耦合业务逻辑必须使用 psr-14 兼容事件分发器,首选官方组件 yiisoft/event-dispatcher;需通过 composer 安装并验证类文件存在,事件须定义为具体对象而非字符串。

要在 Yii 3.0 中实现松耦合、可测试、可扩展的业务逻辑响应,必须放弃 Yii 2.x 的全局事件管理器和 $app->on() 写法,转而使用 PSR-14 兼容的事件分发机制——它不依赖 Application 实例,也不绑定 ServiceLocator,所有监听器都通过 DI 容器注册并按需触发。
确认项目已启用 PSR-14 事件系统
Yii 3.0 默认不内置事件分发器,需显式安装官方事件组件:【yiisoft/event-dispatcher】 是唯一被框架生态正式支持的事件分发实现,其他第三方事件库(如 symfony/event-dispatcher)虽可运行,但无法与 yii-permission、db-migration 等扩展协同工作。
执行命令安装:composer require yiisoft/event-dispatcher
安装后检查 vendor/yiisoft/event-dispatcher/src/ 是否存在 EventDispatcherInterface.php 和 SimpleEventDispatcher 类——若缺失,说明 Composer 缓存损坏,需运行 composer clear-cache && composer install 重拉。
定义自定义事件类
事件必须是具体对象,不能用字符串标识符。例如用户注册成功后需通知多个模块,应新建一个类:
在 src/Events/UserRegistered.php 中写入:
<?php namespace App\Events;use Yiisoft\EventDispatcher\EventInterface;final class UserRegistered implements EventInterface{ public function __construct(public int $userId, public string $email) { }}
注意:必须实现 EventInterface 接口,否则 Dispatcher 不会识别;构造参数建议用 public 属性提升语法,这是 PHP 8.2+ 强制要求,低于该版本将导致 Fatal error。
注册监听器(两种方式任选其一)
方法一:通过容器自动发现(推荐)
在 config/common.php 中添加:
use App\Listeners\SendWelcomeEmail;use App\Listeners\CreateUserProfile;use Yiisoft\EventDispatcher\ListenerProviderInterface;return [ ListenerProviderInterface::class => [ SendWelcomeEmail::class, CreateUserProfile::class, ],];
每个监听器类必须声明类型提示的事件参数,例如:public function __invoke(UserRegistered $event): void —— Dispatcher 会自动匹配事件类型,无需手动绑定。
方法二:手动绑定监听器到事件
若需动态控制监听顺序或条件注册,可在 config/web.php 中使用闭包:
use Yiisoft\EventDispatcher\SimpleEventDispatcher;return [ SimpleEventDispatcher::class => [ 'class' => SimpleEventDispatcher::class, '__construct()' => [ 'listenerProviders' => [ static fn () => [new SendWelcomeEmail(), new CreateUserProfile()], ], ], ],];
在业务逻辑中触发事件
第一步:在控制器或服务类构造函数中注入 EventDispatcherInterface
use Yiisoft\EventDispatcher\EventDispatcherInterface;final class RegistrationService{ public function __construct(private EventDispatcherInterface $eventDispatcher) { }
第二步:创建事件实例并分发
$user = $this->userRepository->save($data);$event = new UserRegistered($user->getId(), $user->getEmail());$this->eventDispatcher->dispatch($event);
第三步:确保监听器执行顺序可控(如邮件必须在档案创建之后发送)
在监听器类上添加 #[\Priority(100)] 属性(数字越大优先级越高),例如:
#[\Priority(200)]final class SendWelcomeEmail{ public function __invoke(UserRegistered $event): void { // 发送邮件逻辑 }}
注意:Priority 属性仅在使用 yiisoft/event-dispatcher v3.0+ 时生效,旧版本忽略该元数据,会导致监听顺序不可控。











