我在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:
提前谢谢!
推荐答案按照这篇文章: forums.laravel.io/viewtopic.php?pid=47380#p47380
as per this post: 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:过滤器内部的引用控制器对象
发布评论