thinkphp 5.0+ 的 Behavior行为AOP

原创
2018/09/07 00:26
阅读数 2.9K

本文介绍如何在thinkphp 5.0+中自定义标签拦截器(即自定义AOP行为)

1、定义一个Behavior处理器\application\index\behavior\Privilege.php

namespace app\index\behavior;


class Privilege
{
    public function run()
    {
        // 默认绑定的标签行为逻辑,如果该类中没有其它显示定义的标签处理方法,此会调用此方法
        echo '   default behavior goes here   ';
    }

    public function customListener1(){
        echo "<br/>".'custom_listener1'."<br/>";
    }

    public function customListener2(){
        echo "<br/>".'custom_listener2'."<br/>";
    }

    public function appEnd()
    {
        echo "<br/>appEnd...<br/>";
    }
}

2、定义Model业务层\application\index\model\User.php,并设置拦截器断点位置

namespace app\index\logic;


use think\Model;

class User extends Model
{

    function user_info(){
        $result  = array('success'=>true,'msg'=>'','data'=>array());

        echo '<br/>do some acton...<br/>';

        \think\Hook::listen('custom_listener1');

        echo '<br/>do another action...<br/>';

        \think\Hook::listen('custom_listener2');

        echo '<br/>all action done.<br/>';

        return $result;
    }
}

3、调用模型\application\index\controller\Index.php ,并激活拦截器(即绑定拦截标签与处理器的关系)

namespace app\index\controller;

use app\index\logic\User;
use think\controller\Rest;

class Index extends Rest
{
    function __construct()
    {
        parent::__construct();
        \think\Hook::add('custom_listener1','app\\index\\behavior\\Privilege');
        \think\Hook::add('custom_listener2','app\\index\\behavior\\Privilege');
    }

    function user_info(){
        /** @var \app\index\logic\User $userLogic */
        $userObj = new User();
        $user_info = $userObj->user_info();

        return 'ok';
    }
}

4、测试效果,访问http://localhost/index/index/user_info 

do some acton...

custom_listener1

do another action...

custom_listener2

all action done.

appEnd...
ok

注意到有 appEnd..输出是因为配置了框架自带的tags.php拦截规则,如

// 应用行为扩展定义文件
return [
    // 应用初始化
    'app_init'     => [],
    // 应用开始
    'app_begin'    => [],
    // 模块初始化
    'module_init'  => [],
    // 操作开始执行
    'action_begin' => [],
    // 视图内容过滤
    'view_filter'  => [],
    // 日志写入
    'log_write'    => [],
    // 应用结束
    'app_end'      => ['app\\index\\behavior\\Privilege'],
    'response_end'      => [],//no effected
];

 

Behavior几个要点 :

1、官方文档描述的几个拦截标签,如app_init,action_begin等,是系统内置支持的,也可以自定义任意的标签,并不局限于官方的几个;

2、要用好Behavior要注意三个步骤:a.处理器的定义(上面的Privilege.php类)、b.埋点标签(即\think\Hook::listen())、c.激活并绑定处理器与埋点标签(即\think\Hook::add()方法)

3、系统定义的拦截标签,激活的地方是有限制的,如app_init标签,如果你在某个controller里激活,是永远不会执行的,因为app_init方法执行时,controller类还没有执行到,所以在controller里定义是无效的,也就是只能在tags.php里配置了。

总结:官方文档关于Behavior描述有点不具体,需要花时间摸索才总结出来,在这记录一下希望对新手有所帮助。

展开阅读全文
加载中

作者的其它热门文章

打赏
0
2 收藏
分享
打赏
0 评论
2 收藏
0
分享
返回顶部
顶部