使用参数手动调用控制器方法并且仍然有方法注入
Manually calling controller method with parameter and still have method injection
如何手动调用 控制器方法 指定一些输入参数,但仍然对未指定的参数进行方法注入工作(下面的示例)。
routes.php
$myController->index($id);
controllers/MyControllerOne.php
class MyControllerOne
{
public function index($id, MyRequest $request)
{
}
}
额外信息
我需要这个的原因是因为我的路由中有特殊信息可以确定应该执行哪个控制器,例如 /myroute/{data}/{id}
。这有点不正统,但考虑到我们系统的范围,这是一个必要的邪恶。
一旦我在路由中解决了需要调用哪个控制器的问题,我就想调用该控制器上的方法。 $controllerInstance->index($id)
.
如果只是请求,我想你可以手动传递这个$this->app->make('Request')
,像这样
$controllerIntance->index($id, $this->app->make('Request'))
请注意,您实际上不必注入 Request,因为您也可以在控制器内部使用 App::make
。但是我不确定这个决定在可测试性和耦合性方面有多好。
更多信息:
此函数从容器中解析 'Request',即实例化或 returns 现有实例(取决于服务提供商的类型)。
使用 make
在此处描述 http://laravel.com/docs/5.0/container (see "Resolving"). I also found this answer helpful, to understanding how the container works
如何手动调用 控制器方法 指定一些输入参数,但仍然对未指定的参数进行方法注入工作(下面的示例)。
routes.php
$myController->index($id);
controllers/MyControllerOne.php
class MyControllerOne
{
public function index($id, MyRequest $request)
{
}
}
额外信息
我需要这个的原因是因为我的路由中有特殊信息可以确定应该执行哪个控制器,例如 /myroute/{data}/{id}
。这有点不正统,但考虑到我们系统的范围,这是一个必要的邪恶。
一旦我在路由中解决了需要调用哪个控制器的问题,我就想调用该控制器上的方法。 $controllerInstance->index($id)
.
如果只是请求,我想你可以手动传递这个$this->app->make('Request')
,像这样
$controllerIntance->index($id, $this->app->make('Request'))
请注意,您实际上不必注入 Request,因为您也可以在控制器内部使用 App::make
。但是我不确定这个决定在可测试性和耦合性方面有多好。
更多信息:
此函数从容器中解析 'Request',即实例化或 returns 现有实例(取决于服务提供商的类型)。
使用 make
在此处描述 http://laravel.com/docs/5.0/container (see "Resolving"). I also found this answer helpful, to understanding how the container works