webman event
1.0.0
事件相比較中間件的優勢是事件比中間件更精準定位(或者說粒度更細),並且更適合一些業務場景的擴展。例如,我們通常會遇到用戶註冊或登入後需要做一系列操作,透過事件系統可以做到不侵入原有程式碼完成登入的操作擴展,降低系統的耦合性的同時,也降低了BUG的可能性。
composer require tinywan/event
事件類LogErrorWriteEvent.php
namespace extend ;
use Symfony Contracts EventDispatcher Event ;
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 ' => [
extend LogErrorWriteEvent:: NAME => extend LogErrorWriteEvent::class,
extend DingTalkEvent:: NAME => extend DingTalkEvent::class,
],
];
訂閱類別LoggerSubscriber.php
namespace extend ;
use Symfony Component EventDispatcher EventSubscriberInterface ;
use Symfony Contracts EventDispatcher Event ;
class LoggerSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents (): array
{
// 监听的不同事件,当事件触发时,会调用 onResponse 方法
return [
extend LogErrorWriteEvent:: NAME => ' onResponse ' ,
extend DingTalkEvent:: NAME => ' onResponse ' ,
];
}
/**
* @desc: 触发事件
* @param Event $event
*/
public function onResponse ( Event $ event )
{
// 一些具体的业务逻辑
var_dump ( $ event -> handle ());
}
}
事件訂閱
return [
// 事件订阅
' subscriber ' => [
extend LoggerSubscriber::class
],
];
觸發LogErrorWriteEvent
事件。
$ error = [
' errorMessage ' => '错误消息' ,
' errorCode ' => 500
];
Tinywan Event:: trigger ( new extend LogErrorWriteEvent ( $ error ), extend LogErrorWriteEvent:: NAME );
$ error = [
' errorMessage ' => '错误消息' ,
' errorCode ' => 500
];
event ( new extend LogErrorWriteEvent ( $ error ), extend LogErrorWriteEvent:: NAME );
執行結果
This project is licensed under the Apache 2.0 license.