1

if I have a function somewhere like:

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

then call it somewhere else with:

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

PHPstorm gives me a sgwiggly line and says "Required paramater $param2 is missing" message.

Does this sort of thing only work in a controller or can I make it work elsewhere? Or will it work if I ran it and PHPstorm just thinks it doesn't?

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

Nicekiwi
  • 4,567
  • 11
  • 49
  • 88

1 Answers1

0

Yes, you can use method injection anywhere, but you have to call the method through the a Container. Just like you use \App::make() to resolve a class instance through the container, you can use \App::call() to call a method through the container.

You can inspect the function in Illuminate/Container/Container.php to get all the details, but in general the first parameter is the method to call and the second parameter is an array of parameters to pass. If an associative array is used, the parameters will be matched up by name and the order won't matter. If an indexed array is used, the injectable parameters must be first in the method definition, and the parameter array will be used to fill in the rest. Examples below.

Given the following class:

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

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

You can use method injection in the following ways:

$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.
patricus
  • 59,488
  • 15
  • 143
  • 145