1. 事件系统概述
ThinkPHP8的事件系统基于观察者模式实现,用于实现应用中的解耦和异步处理。
2. 三种方式的用途和区别
2.1 事件绑定 (Event Binding)
用途 将事件类直接绑定到监听器,是最直接的事件处理方式。
特点:
-
一对一或多对一的关系
-
直接关联事件类和监听器
-
配置简单直观
示例配置 (event.php):
return [
// 事件绑定
'bind' => [
'app\event\UserLogin' => [
'app\listener\SendNotification',
'app\listener\RecordLoginLog',
],
],
];
2.2 事件监听 (Event Listening)
用途: 通过事件标识来监听事件,更灵活的事件处理方式。
特点:
-
使用事件标识符而非具体事件类
-
支持通配符监听
-
更灵活的事件管理
示例配置:
return [
// 事件监听
'listen' => [
'UserLogin' => [
'app\listener\SendNotification',
'app\listener\RecordLoginLog',
],
'UserLogout' => [
'app\listener\ClearSession',
],
// 通配符监听
'app\admin\event\*' => [
'app\admin\listener\AdminActionLog',
],
],
];
2.3 事件订阅 (Event Subscribe)
用途: 在一个订阅者类中统一管理多个事件监听。
特点:
-
集中管理相关事件
-
类方法作为事件处理器
-
代码组织更清晰
示例配置:
return [
// 事件订阅
'subscribe' => [
'app\subscribe\UserSubscribe',
'app\subscribe\OrderSubscribe',
],
];
3. 具体实现示例
3.1 事件绑定示例
事件类 (app/event/UserLogin.php):
<?php
namespace app\event;
class UserLogin
{
public $user;
public $loginTime;
public function __construct($user)
{
$this->user = $user;
$this->loginTime = time();
}
}
监听器类 (app/listener/SendNotification.php):
<?php
namespace app\listener;
use app\event\UserLogin;
class SendNotification
{
public function handle(UserLogin $event)
{
// 发送登录通知
$user = $event->user;
echo "发送登录通知给: " . $user['name'] . "\n";
echo "登录时间: " . date('Y-m-d H:i:s', $event->loginTime) . "\n";
}
}
触发事件:
// 触发绑定的事件
event('app\event\UserLogin', new \app\event\UserLogin($user));
// 或者使用助手函数
event(new \app\event\Us

最低0.47元/天 解锁文章
3375

被折叠的 条评论
为什么被折叠?



