以Ruby on Rails为例。
class SomeController < ApplicationController
before_filter :generateRandomValue
def generateRandomValue
//generates a random value between 0 and 10
end
def getBoo
//Return value generated by the method above
end
end
如果我们调用 getBoo
,类将首先运行generateRandomValue
因为它在过滤器之前有一个通用的作用域。
我们还可以在Ruby on Rails中的过滤器之前对其进行调整,例如;
method x,y,z runs before a method.
method 1,2,3 runs before b,c,d method.
method always, always runs. (think it like PHP's __construct())
有没有办法在 Laravel 4 中的控制器方法调用之前设置过滤器?
主要原因是,我想通过在过滤器之前应用来干燥我的大部分代码。
谢谢。
是的
- 这是 Laravel 4 中的一个新功能。
泰勒在这里有一个很好的视频,你可以观看 - 它显示了它的实际效果和要使用的代码。
但一般来说,你只需向构造函数添加一个过滤器:
Class ExampleController extends BaseController
{
public function __construct()
{
$this->beforeFilter('myfilter');
$this->beforeFilter('anotherfilter')->only('getBoo');
}
}