thinkphp6事件訂閱,監聽多個事件
-
- 創建一個事件類
- 創建一個監聽類
- 修改配置文件確定觸發事件
創建一個事件類
php think make:event User
<?php namespace app\event; class User { public function __construct() { echo '<br>我是用戶的登陸事件構造函數<br>'; } public function login_event() { echo '我是login_event<br>'; } }
創建一個監聽類
php think make:listener User
<?php namespace app\listener; class User { //依賴注入的方法 public function handle(\app\event\User $event) { echo 'listener監聽得到:' . $event->login_event() . '<br>'; } }
控制器中調用監聽事件並觸發
use think\facade\Event; public function hellolisten($name = 'ThinkPHP6') { echo '<br>hellolisten=' . $name; //監聽類 Event::listen('UserListener','app\listener\User'); //也可以寫到配置文件 event.php 的listen 數組 //觸發監聽事件 Event::trigger('UserListener'); }
修改配置文件確定觸發事件
修改event.php 配置文件,增加監聽事件
創建兩個監聽類,如下圖:
UserLogout.php
<?php namespace app\listener; class UserLogout { public function handle() { echo 'UserLogout監聽'; } }
UserLogin.php
<?php namespace app\listener; class UserLogin { public function handle() { echo 'UserLogin監聽'; } }
確定觸發事件的地方,這里為index控制器hellolisten方法
public function hellolisten($name = 'ThinkPHP6') { echo "開始位置<br>"; //直接使用事件類觸發 Event::trigger('UserLogin'); Event::trigger('UserLogout'); echo "<br>結束位置<br>"; }
轉 : https://blog.csdn.net/guo_qiangqiang/article/details/114789465
參考 :
https://www.kancloud.cn/manual/thinkphp6_0/1037492
https://www.kancloud.cn/cyuemcz/xiaobai/1059791