我有一个类,我将其与路由参数一起注入(inject) Controller 。然后我使用 setter 在类中设置路由参数。
路线
Route::get('path/of/url/with/{paramVar}', 'testController@testFunc)
Controller
class testController
{
public function testFunc(MyClassInterface $class, $routeParamVar)
{
$class->setParam($routeParamVar);
//do stuff here
...
服务提供者
public function register()
{
$this->bind('path\to\interface', 'path\to\concrete');
}
相反,我想将路由参数注入(inject)到我要注入(inject) Controller 的类的构造函数中。我知道from this question我需要使用 laravel 容器。
我可以使用
Request::class
注入(inject)其他路由参数,但是如何注入(inject)路由路径参数?我想我最终会得到这样的东西
class testController
{
public function testFunc(MyClassInterface $class)
{
//do stuff here
...
最佳答案
您可以使用 $router->input('foo')
函数来检索服务容器中的路由参数。
https://laravel.com/api/master/Illuminate/Routing/Router.html#method_input
因此,在您的服务提供商中:
public function register()
{
$this->bind('path\to\interface', function(){
$param = $this->app->make('router')->input('foo');
return new path\to\concrete($param);
});
}
关于您的评论,它不会减少太多代码,但在这种情况下最好创建第二个服务提供商,例如
FooValueServiceProvider
谁的实现的唯一工作是从路由器中检索该参数。然后在每个绑定(bind)中,您可以解析 FooValueServiceProvider
并从中检索值。然后稍后如果您更改路由参数的名称,或者需要从路由以外的其他地方解析它,您只需更改该提供程序的实现即可。我不知道您是否可以比每次绑定(bind)多一行代码更有效率,但至少这样可以将其更改为不同的方法。
关于laravel - 路由参数的构造函数注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35266013/