【问题标题】:Calling controllers dynamically动态调用控制器
【发布时间】:2013-06-18 02:28:15
【问题描述】:

我正在尝试在 Laravel 中为我的控制器创建动态路由 - 我知道这可以在 Kohana 中完成,但我试图让它与 Laravel 一起使用没有成功。

这就是我现在拥有的:

Route::get('/{controller}/{action?}/{id?}'...

所以我想打电话给controller/method($id)

理想情况下,这是我想做的:

Route::get('/{controller}/{action?}/{id?}', $controller . '@' . $action);

并让它动态调用 $controller::$action。

我试过这样做:

Route::get('/{controller}/{action?}/{id?}', function($controller, $action = null, $id = null)
{
    $controller = new $controller();
    $controller->$action();
});

但我收到一条错误消息:类控制器不存在。 因此,当控制器扩展 BaseController 时,Laravel 似乎没有包含所有必要的文件。

如果我使用$controller::$action(),它会告诉我我不能静态调用非静态函数。

关于如何完成这项工作的任何想法?

【问题讨论】:

    标签: laravel laravel-4


    【解决方案1】:

    您可以一举自动注册所有控制器:

    Route::controller( Controller::detect() );
    

    如果您使用的是 Laravel 4(正如您的标签所暗示的那样),则不能再使用 Controller::detect()。你必须manually register all the controllers you want to use

    【讨论】:

      【解决方案2】:

      在得知 Laravel 不再支持这个之后,我想出了这个解决方案:

      $uri = $_SERVER['REQUEST_URI'];
      $results = array();
      preg_match('#^\/(\w+)?\/?(\w+)?\/?(\w+)?\/?#', $_SERVER['REQUEST_URI'], $results);
      
      // set the default controller to landing
      $controller = (empty($results[1])) ? 'landing' : $results[1];
      
      // set the default method to index
      $method = (empty($results[2])) ? 'index' : $results[2];
      
      Route::get('{controller?}/{action?}/{id?}', $controller . '@' . $method);
      
      // now we just need to catch and process the error if no controller@method exists.
      

      【讨论】:

        猜你喜欢
        • 2018-07-07
        • 1970-01-01
        • 2015-09-16
        • 1970-01-01
        • 2019-01-18
        • 2012-10-28
        • 2011-05-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多