Laravel 4 控制器前后功能
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16317784/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel 4 Controller Before and After function
提问by Yahia Reyhani
I have a Base Controller that all other controllers will extend it. I want to do some theme and validation and also loading widgets in its Before function.
我有一个基本控制器,所有其他控制器都会扩展它。我想做一些主题和验证,并在它的 Before 函数中加载小部件。
I know that i could handle this with Routes filter but i don't want to place my code inside router i want to every controllers actions first execute "Before function" and then execute "After function" of this Base controller like Laravel 3.
我知道我可以使用 Routes 过滤器处理这个问题,但我不想将我的代码放在路由器中,我希望每个控制器的动作首先执行“Before function”,然后像 Laravel 3 一样执行这个 Base 控制器的“After function”。
class FrontController extends \BaseController {
protected $layout = 'home.index';
public function __construct() {
}
public function before() {
// Do some theme and validation
}
public function __call($method, $parameters) {
return Response::abort('404');
}
Update : I'm looking for a way that for example I could change theme based on a page config or load sidebars widgets after main controller completed its function and ... Because of that I want to access to $this.
更新:我正在寻找一种方法,例如我可以根据页面配置更改主题或在主控制器完成其功能后加载侧边栏小部件......因此我想访问 $this。
回答by BenjaminRH
According to the documentation, you can define before and after methods in your controllers in two ways.
根据文档,您可以通过两种方式在控制器中定义 before 和 after 方法。
With a filter name:
使用过滤器名称:
$this->beforeFilter('auth');
$this->afterFilter('something_else');
or with a closure:
或关闭:
$this->beforeFilter(function() {
// code
});
These would go in your base controller's __construct
method.
这些将进入您的基本控制器的__construct
方法。
Here's a complete example:
这是一个完整的例子:
class BaseController extends Controller {
public function __construct()
{
// Always run csrf protection before the request when posting
$this->beforeFilter('csrf', array('on' => 'post'));
// Here's something that happens after the request
$this->afterFilter(function() {
// something
});
}
/**
* Setup the layout used by the controller.
*
* @return void
*/
protected function setupLayout()
{
if ( ! is_null($this->layout))
{
$this->layout = View::make($this->layout);
}
}
}