Laravel 4: Reference controller object inside filter

北城以北 提交于 2019-12-09 03:30:58

问题


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. The controller object where the filter is running at.
  2. The custom variable from that specific controller ($customVariable).

Thanks in advance!


回答1:



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');
}]);

and

//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');
}

EDIT:

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;
    });
}

}

EDIT 2 :

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.




回答2:


If you declare it as static in your controller, you can call it statically from outside the controller

Controller:

class SampleController extends BaseController
{
    public static $customVariable = 'test';
}

Outside your controller

echo SampleController::$customVariable




回答3:


use:

public function __construct()
{

    $this->beforeFilter('auth', ['controller' => $this]);
}


来源:https://stackoverflow.com/questions/18093861/laravel-4-reference-controller-object-inside-filter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!