Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 307
Dima Vergunov Avatar asked Jan 13 '15 19:01

Dima Vergunov


People also ask

What is method injection in Laravel?

In Laravel, dependency injection is the process of injecting class dependencies into a class through a constructor or setter method. This allows your code to look clean and run faster. Dependency injection involves the use of a Laravel service container, a container that is used to manage class dependencies.

Does Laravel use dependency injection?

The Laravel service container is a powerful tool for managing class dependencies and performing dependency injection. Dependency injection is a fancy phrase that essentially means this: class dependencies are "injected" into the class via the constructor or, in some cases, "setter" methods.

What is __ construct in Laravel?

PHP - The __construct FunctionA constructor allows you to initialize an object's properties upon creation of the object. If you create a __construct() function, PHP will automatically call this function when you create an object from a class.

What is IOC container in Laravel?

The Laravel inversion of control container is a powerful tool for managing class dependencies. Dependency injection is a method of removing hard-coded class dependencies. Instead, the dependencies are injected at run-time, allowing for greater flexibility as dependency implementations may be swapped easily.


1 Answers

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']);
like image 166
Marty Aghajanyan Avatar answered Nov 02 '22 07:11

Marty Aghajanyan