繁体   English   中英

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

[英]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

是的,您可以在任何地方使用方法注入,但是必须通过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.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM