我可以在控制器之外使用方法依赖注入吗?


can I use method dependency injection outside of a controller?

如果我有一个函数,如:

public function test(Request $request, $param1, $param2)    

然后在其他地方调用:

$thing->test('abc','def')

PHPstorm给了我一个歪歪斜歪的行,说"必需的参数$param2丢失"的消息。

这种东西只在控制器中工作还是我可以让它在其他地方工作?或者如果我运行它而PHPstorm认为它不起作用,它会起作用吗?

http://laravel.com/docs/5.0/controllers dependency-injection-and-controllers

是的,您可以在任何地方使用方法注入,但您必须通过a Container调用该方法。就像您使用'App::make()通过容器解析类实例一样,您可以使用'App::call()通过容器调用方法。

您可以检查Illuminate/Container/Container.php中的函数以获得所有细节,但通常第一个参数是要调用的方法,第二个参数是要传递的参数数组。如果使用关联数组,则参数将按名称匹配,顺序无关紧要。如果使用索引数组,则可注入的参数必须首先出现在方法定义中,然后使用参数数组填充其余部分。下面的例子。

给定以下类:

class Thing {
    public function testFirst(Request $request, $param1, $param2) {
        return func_get_args();
    }
    public function testLast($param1, $param2, Request $request) {
        return func_get_args();
    }
}

可以通过以下方式使用方法注入:

$thing = new Thing();
// or $thing = App::make('Thing'); if you want.
// ex. testFirst with indexed array:
// $request will be resolved through container;
// $param1 = 'value1' and $param2 = 'value2'
$argsFirst = App::call([$thing, 'testFirst'], ['value1', 'value2']);
// ex. testFirst with associative array:
// $request will be resolved through container;
// $param1 = 'value1' and $param2 = 'value2'
$argsFirst = App::call([$thing, 'testFirst'], ['param1' => 'value1', 'param2' => 'value2']);
// ex. testLast with associative array:
// $param1 = 'value1' and $param2 = 'value2'
// $request will be resolved through container;
$argsLast = App::call([$thing, 'testLast'], ['param1' => 'value1', 'param2' => 'value2']);
// ex. testLast with indexed array:
// this will throw an error as it expects the injectable parameters to be first.