How method injection works in Laravel 5(I mean implementation), can I inject parameters in custom method, not just in controller actions?
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.
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.
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.
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) 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']);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With