thinkphp6 订阅
event.php
<?php // 事件定义文件 return [ 'bind' => [ 'UserLogin' => 'app\event\UserLogin', 'UserLogout' => 'app\event\UserLogin', ], 'listen' => [ 'AppInit' => [], 'HttpRun' => [], 'HttpEnd' => [], 'LogLevel' => [], 'LogWrite' => [], ], 'subscribe' => [ 'app\subscribe\User', ], ];
app\event\UserLogin.php
<?php declare (strict_types = 1); namespace app\event; use app\model\User; class UserLogin { public $user; public function __construct(User $user) { $this->user = $user; } }
app\subscribe\User.php
<?php declare (strict_types=1); namespace app\subscribe; use think\Event; class User { public function onUserLogin($user) { var_dump($user); echo 5; // UserLogin事件响应处理 } public function onUserLogout($user) { var_dump($user); echo 4; // UserLogout事件响应处理 } public function subscribe(Event $event) { $event->listen('UserLogout', [$this, 'onUserLogout']); $event->listen('UserLogin', [$this, 'onUserLogin']); } }
控制器
<?php
namespace app\controller\admin;
use app\event\UserLogin;
use app\model\User;
use think\Request;
class Index extends Base
{
public function index(Request $request){
$userObj = new User();
$user = $userObj->where('id',1)->find();
event(new UserLogin($user));
event(\app\subscribe\User::class);
echo '这是首页';
}
}