webman event
1.0.0
事件相比较中间件的优势是事件比中间件更加精准定位(或者说粒度更细),并且更适合一些业务场景的扩展。例如,我们通常会遇到用户注册或者登录后需要做一系列操作,通过事件系统可以做到不侵入原有代码完成登录的操作扩展,降低系统的耦合性的同时,也降低了BUG的可能性。
composer require tinywan/event
事件类 LogErrorWriteEvent.php
namespace extend;
use SymfonyContractsEventDispatcherEvent;
class LogErrorWriteEvent extends Event
{
const NAME = 'log.error.write'; // 事件名,事件的唯一标识
public $log;
public function __construct(array $log)
{
$this->log = $log;
}
public function handle()
{
return $this->log;
}
}
事件监听
return [
// 事件监听
'listener' => [
extendLogErrorWriteEvent::NAME => extendLogErrorWriteEvent::class,
extendDingTalkEvent::NAME => extendDingTalkEvent::class,
],
];
订阅类 LoggerSubscriber.php
namespace extend;
use SymfonyComponentEventDispatcherEventSubscriberInterface;
use SymfonyContractsEventDispatcherEvent;
class LoggerSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents(): array
{
// 监听的不同事件,当事件触发时,会调用 onResponse 方法
return [
extendLogErrorWriteEvent::NAME => 'onResponse',
extendDingTalkEvent::NAME => 'onResponse',
];
}
/**
* @desc: 触发事件
* @param Event $event
*/
public function onResponse(Event $event)
{
// 一些具体的业务逻辑
var_dump($event->handle());
}
}
事件订阅
return [
// 事件订阅
'subscriber' => [
extendLoggerSubscriber::class
],
];
触发 LogErrorWriteEvent
事件。
$error = [
'errorMessage' => '错误消息',
'errorCode' => 500
];
TinywanEvent::trigger(new extendLogErrorWriteEvent($error), extendLogErrorWriteEvent::NAME);
$error = [
'errorMessage' => '错误消息',
'errorCode' => 500
];
event(new extendLogErrorWriteEvent($error), extendLogErrorWriteEvent::NAME);
执行结果
This project is licensed under the Apache 2.0 license.