Laravel 4:过滤器内部的引用控制器对象 [英] Laravel 4: Reference controller object inside filter

查看:60
本文介绍了Laravel 4:过滤器内部的引用控制器对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Laravel 4中有一个控制器,其中声明了一个自定义变量.

I have a controller in Laravel 4, with a custom variable declared within it.

class SampleController extends BaseController{
      public $customVariable;
}

两个问题:在路由过滤器中我可以通过任何方式致电

Two questions: Is there any way I can call within a route filter:

  1. 运行过滤器的控制器对象.
  2. 该特定控制器的自定义变量($ customVariable).

提前谢谢!

推荐答案


按照这篇文章:
http://forums.laravel.io/viewtopic.php?pid=47380#p47380


as per this post:
http://forums.laravel.io/viewtopic.php?pid=47380#p47380

您只能将参数作为字符串传递给过滤器.

You can only pass parameters to filters as strings.

//routes.php
Route::get('/', ['before' => 'auth.level:1', function()
{
return View::make('hello');
}]);

//filters.php
Route::filter('auth.level', function($level)
{
   //$level is 1
});

在控制器中,它看起来更像这样

In controllers, it would look more like this

public function __construct(){
   $this->filter('before', 'someFilter:param1,param2');
}

如果这不能满足您的需求,则可以始终在控制器的构造函数中定义过滤器.如果您需要访问当前控制器($ this)及其自定义字段,并且想拥有许多不同的类,则可以将过滤器放入BaseController的构造函数中,并将其扩展到所需的所有类中.

Should this not suffice to your needs, you can allways define the filter inside the controller's constructor. If you need access to the current controller ($this) and it's custom fields and you have many different classes you want to have that in, you can put the filter in BaseController's constructor and extend it in all classes you need.

class SomeFancyController extends BaseController {

protected $customVariable

/**
 * Instantiate a new SomeFancyController instance.
 */
public function __construct()
{
    $ctrl = $this;
    $this->beforeFilter(function() use ($ctrl)
    {
        //
        // do something with $ctrl
        // do something with $ctrl->customVariable;
    });
}

}

根据您的新问题,我意识到上面的示例有一个小错误-因为我忘记了闭包具有局部作用域.所以我猜现在是对的.

As per your new question I realised the above example had a small error - as I forgot the closure has local scope. So it's correct now I guess.

这篇关于Laravel 4:过滤器内部的引用控制器对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆