duanping1920 2014-12-07 13:39
浏览 54
已采纳

在Laravel 5中将路由器注入控制器方法

Does anyone know why can't one use controller method injection in Laravel 5 to make the $router singleton available inside a controllers method, like in the code below?

use Illuminate\Routing\Router;

class WelcomeController extends Controller {
    // ...
    public function test($name = 'default var value', Router $router)
    {
        // stuff like taking the {name} part of /say-hello-to/{name?}
        // ...using $router->input('name') for example
        // ...assuming a route like: Route::get('say-hello-to/{name?}', 'WelcomeController@test') 
    }
}

An alternative way to get the same thing (idiomatic access to an url part inside a controller method) is useful, but I've already thought of a way to do this and I'm mainly interested in why this doesn't just work, as what I'm trying to get is a deeper understanding of how Laravel works and what advanced patterns can one emply when working with it.

  • 写回答

1条回答 默认 最新

  • douyan4243 2014-12-07 14:03
    关注

    OK, I first thought about deleting this after I figured out the answer myself in ~5min, but then again, maybe it's better to write this for others to be able to google:

    When combining optional URL arguments (like 'test/{name?}') with controller method injection, always put the injected parameters before the ones with default values in the method declaration, otherwise you will end up staring at some pretty confusing errors when accessing the URL variant without the optional parameter.

    So, in the example above, it should have been:

    public function test(Router $router, $name = 'default var value')

    ...instead of:

    public function test($name = 'default var value', Router $router)

    And, btw, if someone more experienced with Laravel than me comes across this, please comment if you think this is a Laravel 5 bug that should be reported to the developers, or if you think this is the intended behavior for such situations.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog