Laravel 控制器前置方法与后置方法的代码变更设置
进入laravel的核心文件 vendor\laravel\framework\src\Illuminate\Routing\Controller.php
查找到方法 callAction:
源码为:
public function callAction($method, $parameters)
{
return calluserfuncarray([$this, $method], $parameters);
}
改成:
public function callAction($method, $parameters)
{
if(methodexists($this,'beforeAction')) calluserfuncarray([$this, 'beforeAction'], ['action' => $method]);
$return = calluserfuncarray([$this, $method], $parameters);
if(methodexists($this,'afterAction')) calluserfuncarray([$this, 'afterAction'], ['action' => $method]);
return $return;
}
那么在控制器写,例如:
页面效果为:
日志执行顺序为:
前置方法与后置方法可以为空。
方法名字建议使用定义常量的方式来检测。方便后续扩展。
写这个后置是为了,自己准备进行事件绑定,但是不想每个方法去写,准备写一个类来设置进行对不同方法,不同监听事件。
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: