在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);
    }

}

參考內容

相關文章
相關標籤/搜索