文件分布示意
创建钩子文件
data/behavior/AopTest.php
<?php
namespace data\behavior;
class AopTest
{
//绑定api初始化
public function apiInit($params){
echo 'api初始化开始';
}
//绑定api结束
public function apiEnd($params){
echo 'api初始化结束';
}
}
配置钩子
application/tags.php
<?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.php
<?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初始化结束