ThinkPHP8 事件系统详解:bind、listen、subscribe

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

漫游游²º¹²

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值