使用助手函数注册事件
<?php
namespace appindexcontroller;
use appindexmodelUser;
class Index
{
public function Index(){
// 触发UserLogin事件 使用助手函数
event('UserLogin');
return "ming";
}
}
生成事件类
php think make:event UserLogin
事件类添加方法
<?php
namespace appevent;
use appindexmodelUser;
class UserLogin{
public $user;
public function _construct(User $user){
$this->user = $user;
}
}
这里依赖于model目录下的User类
事件类添加事件标识
此时目录如下
添加标识
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// 事件定义文件
return [
'bind' => [
'UserLogin' => 'appeventUserLogin',
],
'listen' => [
'AppInit' => [],
'HttpRun' => [],
'HttpEnd' => [],
'LogLevel' => [],
'LogWrite' => [],
],
'subscribe' => [
],
];
此时访问 http://localhost:8082/ 可以发现已经访问成功
事件监听
手动注册一个事件监听
/**
* 事件监听
*/
public function listen(){
Event::listen('UserLogin', function ($user){
});
}
可以使用命令行生成事件监听
php think make:listener UserLogin