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

Php 我可以在控制器之外使用方法依赖项注入吗?,php,laravel,laravel-5,Php,Laravel,Laravel 5,如果我有一个函数,比如: public function test(Request $request, $param1, $param2) 然后在其他地方使用以下命令调用它: $thing->test('abc','def') PHPstorm给了我一条粗线条,并说“缺少必需的参数$param2”消息 这类事情只在控制器中工作,还是我可以在其他地方工作?或者,如果我运行了它,而PHPstorm认为它不起作用,它会起作用吗 是的,您可以在任何地方使用方法注入,但必须通过a容器调用

如果我有一个函数,比如:

public function test(Request $request, $param1, $param2)    
然后在其他地方使用以下命令调用它:

$thing->test('abc','def')
PHPstorm给了我一条粗线条,并说“缺少必需的参数$param2”消息

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


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

您可以在
illumb/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.