Skip to content
Advertisement

Laravel 5 – Method injection

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

Advertisement

Answer

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('AppHttpControllersApimyTestFunction');

or for methods

App::call([$object, 'myTestMethod']);
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement