简单说明
在控制器类中设置 beforeActionList 属性来达到目的,这个属性是一个数组,可以继续为每一个元素在此进行限制
表示这些方法不使用前置方法:
<?php['except' => '方法名,方法名']
表示只有这些方法使用前置方法:
<?php['only' => '方法名,方法名']
测试用例
常见的错误一忘记继承基类
路由:
<?phpuse think\facade\Route;/*** 对应 test 模块使用的路由定义文件*/Route::get('test/main', 'test/Prefix/main');
控制器:
<?phpnamespace app\test\controller;class Prefix{protected $beforeActionList = ['first','second','three',];protected function first(){echo 'first <br/>';}protected function second(){echo 'second <br/>';}protected function third(){echo 'third <br/>';}public function main(){echo 'main';}}
postman 测试:发现并不是我们想得那样,在访问 main 的时候,一次调用 beforeActionList 属性设置的 first() 、seond()、third() 方法
正确的使用方式
上面我犯了一个常见的错误,自定义的控制器使用前置操作之前没有去继承基类 \think\Controller.php.
改写一下 控制器:
<?phpuse think\Controller;class Prefix extends Controller{// ... ...protected $beforeActionList = ['first','second','third',];// ... ...}
再次测试:一切都正常了
使用 only 限制前置操作
控制器:
<?phpprotected $beforeActionList = ['first' => ['only' => 'go'],'second','third',];
postman 测试:
使用 except 限制前置操作
控制器:
<?phpprotected $beforeActionList = ['first' => ['only' => 'go'],'second' => ['except' => 'main'],'third',];
postman 测试:
