webman event
1.0.0
The advantage of events compared to middleware is that events are more accurately positioned (or more granular) than middleware, and are more suitable for the expansion of some business scenarios. For example, we usually encounter users who need to perform a series of operations after registering or logging in. Through the event system, we can complete the login operation expansion without invading the original code, which not only reduces the coupling of the system, but also reduces the possibility of BUG. .
composer require tinywan/event
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 ;
}
}
event listening
return [
// 事件监听
' listener ' => [
extend LogErrorWriteEvent:: NAME => extend LogErrorWriteEvent::class,
extend DingTalkEvent:: NAME => extend DingTalkEvent::class,
],
];
Subscription 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 ());
}
}
event subscription
return [
// 事件订阅
' subscriber ' => [
extend LoggerSubscriber::class
],
];
Trigger the LogErrorWriteEvent
event.
$ 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 );
Execution result
This project is licensed under the Apache 2.0 license.