Laravel 4:过滤器内部的引用控制器对象

编程入门 行业动态 更新时间:2024-10-10 04:23:57
本文介绍了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:

  • 运行过滤器的控制器对象.
  • 该特定控制器的自定义变量($ customVariable).
  • 提前谢谢!

    推荐答案

    按照这篇文章: 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:过滤器内部的引用控制器对象

    本文发布于:2023-11-17 11:13:42,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1609830.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:过滤器   控制器   对象   Laravel

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!