事件就是把一些要做的事封装起来,哪里要用就去调用这个事件
事件类不用生成也能触发(event);
事件监听:事件监听是一个一个生成的,一个事件监听负责一件事
事件订阅:事件订阅,一个类里面可以定义多个事件监听
例子:
定义事件订阅
<?php
declare (strict_types = 1);
namespace app\subscribe;
class User
{
public function onUserLogin($user)
{
dump('监听UserLogin');
// UserLogin事件响应处理
}
public function onUserLogout($user)
{
dump('监听UserLogout');
// UserLogout事件响应处理
}
}
定义事件监听
<?php
declare (strict_types = 1);
namespace app\listener;
class UserLogin
{
/**
* 事件监听处理
*
* @return mixed
*/
public function handle($event)
{
dump('listener监听');
//
}
}
event.php
<?php
// 事件定义文件
return [
'bind' => [
// 'UserLogin' => 'app\event\UserLogin',
// 更多事件绑定
],
'listen' => [
'UserLogin' => ['app\listener\UserLogin'],
// 更多事件监听
],
'subscribe' => [
'app\subscribe\User',
// 更多事件订阅
],
];
注:没生成一个事件监听类就要在event.php加一个listen;而事件订阅可以一个类里写多个事件监听
使用:
public function index(){
event('UserLogin');
event('UserLogout');
Event::listen('UserLogin', 'app\listener\UserLogin');
return View::fetch();
}
打印: