事件相比较中间件的优势是事件比中间件更加精准定位(或者说粒度更细),并且更适合一些业务场景的扩展。例如,我们通常会遇到用户注册或者登录后需要做一系列操作,通过事件系统可以做到不侵入原有代码完成登录的操作扩展,降低系统的耦合性的同时,也降低了BUG的可能性。
定义事件
事件文件放在app/common/listener目录下,接口定义使用框架核心ListenerInterface,文件位置:tmcore/interfaces/ListenerInterface.php
以定义订单完成事件OrderComplete为例,文件路径:app/common/listener/OrderComplete.php
<?php
namespace app\common\listener;
use tmcore\interfaces\ListenerInterface;
/**
* 订单完成事件
*/
class OrderComplete implements ListenerInterface
{
public function handle($event): void
{
}
}配置事件
在根目录app/event.php文件的listen数组中配置
<?php
// 事件定义文件
return [
'listen' => [
'OrderComplete' => [\app\common\listener\OrderComplete::class], //订单完成事件
],
];调用事件
// 使用event函数调用
event('OrderComplete');
// 使用Event静态调用
use think\facade\Event;
Event::event('OrderComplete',['order_no' => $order_no]);内置事件
<?php
// 事件定义文件
return [
'bind' => [
],
'listen' => [
'AppInit' => [],
'HttpRun' => [],
'HttpEnd' => [],
'LogLevel' => [],
'LogWrite' => [],
'UserLogin' => [\app\common\listener\user\Login::class], //会员登录事件
'UserRegister' => [\app\common\listener\user\Register::class], //会员注册事件
'NoticeMsg' => [\app\common\listener\notice\Msg::class], //发送消息事件
'PayCreate' => [\app\common\listener\pay\Create::class], //支付创建事件
'PayNotify' => [\app\common\listener\pay\Notify::class], //支付回调事件
'PaySuccess' => [\app\common\listener\pay\Success::class], //支付成功事件
'PayRefund' => [\app\common\listener\pay\Refund::class], //支付退款事件
'WechatAuth' => [\app\common\listener\wechat\Auth::class], //微信授权事件
'WechatSubscribe' => [\app\common\listener\wechat\Subscribe::class], //微信订阅事件
],
'subscribe' => [
],
];