Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement dependency injection of Laravel

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces the relevant knowledge of how to achieve Laravel dependency injection, the content is detailed and easy to understand, the operation is simple and fast, and it has a certain reference value. I believe you will gain something after reading this Laravel dependency injection article. Let's take a look at it.

In Laravel, the implementation principle of dependency injection is to use class method reflection to obtain the parameter type, and then use the container to construct an instance, and then use the callback function to call it up; the injection object constructor cannot have parameters, otherwise it will report an error, and dependency injection must be started by the Router class, otherwise it can not be realized by new directly.

This article operating environment: Windows10 system, Laravel6 version, Dell G3 computer.

What is the principle of dependency injection implementation of Laravel?

The laravel container contains control inversion and dependency injection. To use it, you can bind the object first and use make to fetch it directly when needed.

Specific analysis reference: http://laravelacademy.org/post/769.html

Usually our call is as follows.

$config = $container- > make ('config'); $connection = new Connection ($this- > config)

It is easy to understand that this advantage is that there is no need to directly new an instance, the method value has not changed, and the instance can be shared in many places.

But what does this have to do with dependency injection? the real dependency injection does not need to pass any parameter values to the method, but only needs to specify the method parameter type, and the code automatically looks up the relationship and relies on automatic injection.

This feature can be reflected in laravel's Controller, Job, and so on, as follows:

Class TestController extends Controller {public function anyConsole (Request $request, Auth $input) {/ / todo}}

Let's take a look at how he implements automatic dependency injection:

Kernel is called by index.PHP, through multi-layer Kernel pipeline, and then to Router, through multi-layer middleware pipeline. Finally locate to

Line 124 of Illuminate/Routing/Route.php.

Public function run (Request $request) {$this- > container = $this- > container?: new Container; try {if (! Is_string ($this- > action ['uses']) {return $this- > runCallable ($request);} if ($this- > customDispatcherIsBound ()) {return $this- > runWithCustomDispatcher ($request);} return $this- > runController ($request);} catch (HttpResponseException $e) {return $e-> getResponse ();}}

Determine whether $this- > action ['uses'] (format lines such as:\ App\ Http\ Controller\ Datacenter\ RealTimeController@anyConsole) is a string, and $this- > customDispatcherIsBound determines whether a user-defined route is bound. Then jump to $this- > runController ($request).

Protected function runController (Request $request) {list ($class, $method) = explode ('@', $this- > action ['uses']); $parameters = $this- > resolveClassMethodDependencies ($this- > parametersWithoutNulls (), $class, $method); if (! Method_exists ($instance = $this- > container- > make ($class), $method)) {throw new NotFoundHttpException;} return call_user_func_array ([$instance, $method], $parameters);}

The method $this- > resolveClassMethodDependencies can tell from the name that it is the one we are looking for. $this- > parametersWithoutNulls () is to filter empty characters, and $class and $method lines such as:\ App\ Http\ Controller\ Datacenter\ RealTimeController and anyConsole, respectively.

Protected function resolveClassMethodDependencies (array $parameters, $instance, $method) {if (! Method_exists ($instance, $method) {return $parameters;} return $this- > resolveMethodDependencies ($parameters, new ReflectionMethod ($instance, $method);}

New ReflectionMethod ($instance, $method) is the reflection object that gets the class method, see documentation: http://www.php.net/manual/zh/class.reflectionmethod.php

Next jump to line 54 of Illuminate/Routing/RouteDependencyResolverTrait.php.

Public function resolveMethodDependencies (array $parameters, ReflectionFunctionAbstract $reflector) {$originalParameters = $parameters; foreach ($reflector- > getParameters () as $key = > $parameter) {$instance = $this- > transformDependency ($parameter, $parameters, $originalParameters); if (! Is_null ($instance) {$this- > spliceIntoParameters ($parameters, $key, $instance);}} return $parameters;}

The class parameter array is obtained by reflecting the class method, and then traversed and passed to the $this- > transformDependency method. If the instance is not available, call $this- > spliceIntoParameters to know the parameter.

Protected function transformDependency (ReflectionParameter $parameter, $parameters, $originalParameters) {$class = $parameter- > getClass (); if ($class & &! $this- > alreadyInParameters ($class- > name, $parameters)) {return $this- > container- > make ($class- > name);}}

I finally see the shadow of the container, and it is true that the final object is extracted through the container's make method. At this point, the parameters are constructed and will eventually be called back by the call_user_func_array of the runController method.

Summary:

In fact, the principle of dependency injection is to use class method reflection, obtain parameter types, and then use containers to construct instances. Then use the callback function to call it up.

The injection object constructor cannot have parameters. Or you'll make a mistake. Missing argument 1

Dependency injection is fine, but it must be started by the Router class, otherwise it cannot be implemented directly in new. So that's why only Controller and Job classes can use this feature.

This is the end of the article on "how to implement dependency injection of Laravel". Thank you for reading! I believe that everyone has a certain understanding of the knowledge of "how to achieve dependency injection of Laravel". If you want to learn more knowledge, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report