文件分佈示意
建立鉤子文件
data/behavior/AopTest.phpphp
<?php namespace data\behavior; class AopTest { //綁定api初始化 public function apiInit($params){ echo 'api初始化開始'; } //綁定api結束 public function apiEnd($params){ echo 'api初始化結束'; } }
配置鉤子
application/tags.phpthinkphp
<?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 [ // 應用初始化 'app_init' => [ \data\behavior\MessageBehavior::class, \data\behavior\LoadBehavior::class, ], // 應用開始 'app_begin' => [], //接口初始化 'api_init' => [\data\behavior\AopTest::class], 'api_end' => [\data\behavior\AopTest::class], // 模塊初始化 'module_init' => [], // 操做開始執行 'action_begin' => [], // 視圖內容過濾 'view_filter' => [], // 日誌寫入 'log_write' => [], // 應用結束 'app_end' => [], ];
在要加入行爲的類的方法內加入行爲監聽。
application/index/controller/Aop.phpapache
<?php namespace app\index\controller; use think\facade\Hook; use think\Controller; class Aop extends Controller { public function index() { $id = 123; $params1 = '參數1'; $res = Hook::listen('api_init',$params1); echo 'api index'; $params2 = '參數2'; Hook::listen('api_end',$params2); } }
訪問查看輸出效果:
api初始化開始api indexapi初始化結束api