在ThinkPHP5中使用行为

对于一些产品,老是在不停的更改中进行开发的,这样子形成我们的代码乱七八糟的,很不利于阅读和快速入手。 在这里,咱们用什么方法来解决呢?若是你刚好是时用ThinkPHP 5.0+ 或者 Yii 2.0 开发的话,那么哦那恭喜你,咱们是同道中人!php

在 ThinkPHP 5.0 中 使用行为

  • 编写行为文件(命名空间为路径)
namespace app\test\behavior;

use app\common\model\tongji\Cztx;

class Test {
    public function run(&$params) {
        echo json_encode($params);
    }

    public function san(&$a, &$c) {
        echo $a . ' -- ' . $c;
    }

    public function haha() {
        $Cztx = new Cztx();
        $row = $Cztx->get(1);
        echo $row->year;
    }

    public function appInit(&$params) {
        echo 'app_init';
    }

    public function appEnd(&$params) {
        echo 'app_end';
    }
}
  • 在控制器中执行行为
namespace app\Test\controller;

use think\Controller;

class Index extends Controller {

    public function index () {
        $params = 'aaafa';
        $ccc = 'efa';
        \think\Hook::add('appInit','app\\test\\behavior\\Test');
        \think\Hook::add('appEnd','app\\test\\behavior\\Test');
        \think\Hook::add('run','app\\test\\behavior\\Test');
        \think\Hook::add('san','app\\test\\behavior\\Test');
        \think\Hook::add('haha','app\\test\\behavior\\Test');

        \think\Hook::listen('appInit',$params);
        \think\Hook::listen('appEnd',$params);
        \think\Hook::listen('run', $params);
        \think\Hook::listen('san', $params, $ccc);
        \think\Hook::listen('haha', $params, $ccc);
    }

}

参考内容

相关文章
相关标签/搜索