Laravel 控制器前置方法与后置方法的代码变更设置 | Laravel China 社区 - 高品质的 Laravel 和 PHP 开发者社区

[Laravel 控制器前置方法与后置方法的代码变更设置 | Laravel China 社区 - 高品质的 Laravel 和 PHP 开发者社区]

进入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;
}

那么在控制器写,例如:
[](https://lccdn.phphub.org/uploads/images/201807/21/10492/fJOc50oCZD.png?imageView2/2/w/1240/h/0)

[file

](https://lccdn.phphub.org/uploads/images/201807/21/10492/fJOc50oCZD.png?imageView2/2/w/1240/h/0)

页面效果为:
[](https://lccdn.phphub.org/uploads/images/201807/21/10492/VaNFEPrfJU.png?imageView2/2/w/1240/h/0)

[file

](https://lccdn.phphub.org/uploads/images/201807/21/10492/VaNFEPrfJU.png?imageView2/2/w/1240/h/0)

日志执行顺序为:[](https://lccdn.phphub.org/uploads/images/201807/21/10492/dxG3HjEgmB.png?imageView2/2/w/1240/h/0)

[file

](https://lccdn.phphub.org/uploads/images/201807/21/10492/dxG3HjEgmB.png?imageView2/2/w/1240/h/0)

前置方法与后置方法可以为空。
方法名字建议使用定义常量的方式来检测。方便后续扩展。
写这个后置是为了,自己准备进行事件绑定,但是不想每个方法去写,准备写一个类来设置进行对不同方法,不同监听事件。

laravel社区的链接地址


Original url: Access

Created at: 2018-10-10 17:59:37

Category: default

Tags: none

请先后发表评论
  • 最新评论
  • 总共0条评论