<?php namespace app\index\controller; use app\index\model\User; class Index { public function Index(){ // 触发UserLogin事件 使用助手函数 event('UserLogin'); return "ming"; } }
php think make:event UserLogin
<?php namespace app\event; use app\index\model\User; class UserLogin{ public $user; public function _construct(User $user){ $this->user = $user; } }
这里依赖于model目录下的User类php
此时目录以下
thinkphp
添加标识apache
<?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' => 'app\event\UserLogin', ], 'listen' => [ 'AppInit' => [], 'HttpRun' => [], 'HttpEnd' => [], 'LogLevel' => [], 'LogWrite' => [], ], 'subscribe' => [ ], ];
此时访问 http://localhost:8082/ 能够发现已经访问成功app
手动注册一个事件监听函数
/** * 事件监听 */ public function listen(){ Event::listen('UserLogin', function ($user){ }); }
能够使用命令行生成事件监听this
php think make:listener UserLogin