myo*_*yol 5 dependency-injection laravel laravel-5 laravel-5.2
我有一个类,我将它与路由参数一起注入控制器。然后我使用 setter 在类中设置路由参数。
路线
Route::get('path/of/url/with/{paramVar}', 'testController@testFunc)
Run Code Online (Sandbox Code Playgroud)
控制器
class testController
{
public function testFunc(MyClassInterface $class, $routeParamVar)
{
$class->setParam($routeParamVar);
//do stuff here
...
Run Code Online (Sandbox Code Playgroud)
服务提供者
public function register()
{
$this->bind('path\to\interface', 'path\to\concrete');
}
Run Code Online (Sandbox Code Playgroud)
相反,我想将路由参数注入到我注入控制器的类的构造函数中。我从这个问题知道我需要使用 laravel 容器。
我可以使用 注入其他路由参数Request::class,但如何注入路由路径参数?
我想我最终会得到这样的结果
class testController
{
public function testFunc(MyClassInterface $class)
{
//do stuff here
...
Run Code Online (Sandbox Code Playgroud)
您可以使用该$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);
});
}
Run Code Online (Sandbox Code Playgroud)
关于您的评论,它不会减少太多代码,但在这种情况下最好制作第二个服务提供者,例如FooValueServiceProvider谁的实现唯一的工作就是从路由器中检索该参数。然后在每个绑定中,您可以解析 aFooValueServiceProvider并从中检索值。然后,如果您更改路由参数的名称,或者需要从路由以外的其他地方解析它,则只需更改该提供程序的实现。
我不知道您是否可以获得比每个绑定多一行代码更有效的方法,但至少可以通过这种方式将其更改为不同的方法。