7

How method injection works in Laravel 5(I mean implementation), can I inject parameters in custom method, not just in controller actions?

3 Answers 3

13

1) Read this articles to know more about method injection in laravel 5

http://mattstauffer.co/blog/laravel-5.0-method-injection

https://laracasts.com/series/whats-new-in-laravel-5/episodes/2

2) Here is simple implementation of method injection

$parameters = [];
$reflector = new ReflectionFunction('myTestFunction');
foreach ($reflector->getParameters() as $key => $parameter) {
    $class = $parameter->getClass();
    if ($class) {
        $parameters[$key] = App::make($class->name);
    } else {
        $parameters[$key] = null;
    }
}
call_user_func_array('myTestFunction', $parameters);

you can also look at function

public function call($callback, array $parameters = [], $defaultMethod = null)

in https://github.com/laravel/framework/blob/master/src/Illuminate/Container/Container.php file for more details

3) You can use method injection for custom method

App::call('\App\Http\Controllers\Api\myTestFunction');

or for methods

App::call([$object, 'myTestMethod']);
Sign up to request clarification or add additional context in comments.

Comments

2

Here is simple example of method injection,which we often used in laravel.eg

public function show(Request $request,$id){
$record = $request->find($id);
dd($record);
}

-Here we inject object of Request type,and we can inject model class object etc.

Or General Example:

class A{}
class B{
   function abc(A $obj){}
}

-so function abc of class B will accept object of Class A.
like:
$obj = new A();
$obj2 = new B();
$obj2->abc($obj);

Comments

0

Here is one more example in php 7+

class Foo {
   public function bar(Baz $baz)
   {
        $this->custom(...$baz);
   }

   protected function custom(Baz $baz, Baz2 $baz2, Baz3 $baz3)
   {
        return $baz3;
   }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.