简体   繁体   English

我们可以在方法调用之前在过滤器之前添加吗?

[英]Can we add before filters before method calls?

Take this Ruby on Rails example. 以这个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

If we call getBoo , class will run generateRandomValue first because it has a general scoped before filter. 如果我们调用getBoo ,则类将首先运行generateRandomValue因为它在过滤器之前具有常规作用域。

We can also tweak this before filters in Ruby on Rails, like; 我们还可以在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())

Is there any way to set before filters before controller method calls in Laravel 4? 在Laravel 4中调用控制器方法之前,有什么方法可以在过滤器之前设置?

The main reason is, I want to DRY most of my code by applying before filters. 主要原因是,我想通过应用before过滤器来干燥我的大部分代码。

Thank you. 谢谢。

Yes - this is a new feature in Laravel 4. 是的-这是Laravel 4的新功能。

Taylor has a good video on it here you can watch - which shows it in action and the code to use. 泰勒(Taylor)上有一个很好的视频,您可以在这里观看 -该视频演示了它的实际操作和使用的代码。

But in general you just add a filter to your constructor: 但通常,您只需向构造函数添加过滤器即可:

Class ExampleController extends BaseController
{
    public function __construct()
    {
        $this->beforeFilter('myfilter');        
        $this->beforeFilter('anotherfilter')->only('getBoo');       
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM