In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article is about what dependency injection refers to in laravel. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
The term laravel dependency injection, coined by Martin Fowler, is the act of injecting components into an application. Dependency injection is a key element in agile architecture, using examples such as "class UserProvider {protected $connection...}".
This article operating environment: windows7 system, Laravel5.7 version, DELL G3 computer.
Explain dependency injection and IoC in Laravel in detail:
As developers, we have been trying to find new ways to write well-designed and robust code by using design patterns and experimenting with new robust frameworks. In this article, we will explore the dependency injection design pattern through Laravel's IoC components and learn how it can improve our design.
Dependency injection
Dependency injection is a term coined by Martin Fowler, which is an act of injecting components into an application. As Ward Cunningham said:
Dependency injection is a key element in agile architecture.
Let's look at an example:
Class UserProvider {protected $connection; public function _ construct () {$this- > connection = new Connection;} public function retrieveByCredentials (array $credentials) {$user = $this- > connection-> where ('email', $credentials [' email'])-> where ('password', $credentials [' password'])-> first (); return $user }}
If you want to test or maintain this class, you must access an instance of the database to make some queries. To avoid having to do this, you can decouple this class from other classes, and you have one of three options to inject the Connection class without using it directly.
When injecting a component into a class, you can use one of the following three options:
Constructor injection class UserProvider {protected $connection; public function _ construct (Connection $con) {$this- > connection = $con;}... Setter method injection
Similarly, we can use the Setter method to inject dependencies:
Class UserProvider {protected $connection; public function _ _ construct () {...} public function setConnection (Connection $con) {$this- > connection = $con;}. Interface injection interface ConnectionInjector {public function injectConnection (Connection $con);} class UserProvider implements ConnectionInjector {protected $connection; public function _ construct () {...} public function injectConnection (Connection $con) {$this- > connection = $con;}}
When a class implements our interface, we define injectConnection methods to resolve dependencies.
advantage
Now, when testing our class, we can simulate the dependent class and pass it as a parameter. Each class must focus on a specific task and should not be concerned with resolving their dependencies. In this way, you will have a more focused and maintainable application.
If you want to know more about DI, Alejandro Gervassio has introduced it extensively and professionally in this series of articles, so be sure to read these articles. So, what is IoC? IoC (inversion of Control) does not require dependency injection, but it can help you manage dependencies effectively.
Control reversal
Ioc is a simple component that makes it easier to parse dependencies. You can describe an object as a container and automatically inject dependencies every time the class is parsed.
Laravel Ioc
When you request an object, Laravel Ioc has something special in the way it resolves dependencies:
We use a simple example that will be improved in this article.
The SimpleAuth class depends on FileSessionStorage, so our code might look like this:
Class FileSessionStorage {public function _ _ construct () {session_start ();} public function get ($key) {return $_ SESSION [$key];} public function set ($key, $value) {$SESSION [$key] = $value;}} class SimpleAuth {protected $session; public function _ construct () {$this- > session = new FileSessionStorage;}} / / create a SimpleAuth$auth = new SimpleAuth ()
This is a classic approach, so let's start with constructor injection.
Class SimpleAuth {protected $session; public function _ construct (FileSessionStorage $session) {$this- > session = $session;}}
Now let's create an object:
$auth = new SimpleAuth (new FileSessionStorage ())
Now I want to use Laravel Ioc to manage all this.
Because the Application class inherits from the Container class, you can access the container through the App facade.
App::bind ('FileSessionStorage', function () {return new FileSessionStorage;})
The first parameter of the bind method is the unique ID to bind to the container, and the second parameter is a callback function that we can also pass a string representing the name of the class whenever the FileSessionStorage class is executed, as shown below.
Note: if you look at the Laravel package, you will see that bindings are sometimes grouped, such as (view, view.finder... ).
Assuming that we convert the session store to Mysql storage, our class should look like this:
Class MysqlSessionStorage {public function _ construct () {/ /...} public function get ($key) {/ / do something} public function set ($key, $value) {/ / do something}}
Now that we have changed the dependencies, we also need to change the SimpleAuth constructor and bind the new object to the container!
High-level modules should not rely on low-level modules; both should rely on abstract objects.
Abstraction should not depend on details, which should depend on abstractions.
Robert C. Martin
Our SimpleAuth class should not care about how our storage is done, but rather focus on consuming services.
Therefore, we can implement our storage abstractly:
Interface SessionStorage {public function get ($key); public function set ($key, $value);}
This allows us to implement and request an instance of the SessionStorage interface:
Class FileSessionStorage implements SessionStorage {public function _ construct () {/ /...} public function get ($key) {/ /...} public function set ($key, $value) {/ /...} class MysqlSessionStorage implements SessionStorage {public function _ construct () {/ /...} public function get ($key) {/ /...} public function set ($key, $value) {/ /...} class SimpleAuth {protected $session Public function _ _ construct (SessionStorage $session) {$this- > session = $session;}}
If we use App::make ('SimpleAuth') to parse SimpleAuth through the container
Class, the container will throw a BindingResolutionException, attempt to parse the class from the binding, return to the reflection method and resolve all dependencies.
Uncaught exception 'Illuminate\ Container\ BindingResolutionException' with message' Target [SessionStorage] is not instantiable.'
The container is trying to instantiate the interface. We can make a specific binding for the interface.
App:bind ('SessionStorage',' MysqlSessionStorage')
Now every time we try to parse the interface from the container, we get an instance of MysqlSessionStorage. If we want to switch our storage service, we just need to change the binding.
Note: if you want to see if a class is already bound in the container, you can use App::bound ('ClassName'), or you can use App::bindIf (' ClassName') to register a binding that hasn't been registered yet.
Laravel Ioc also provides App::singleton ('ClassName',' resolver') to handle singleton binding.
You can also use App::instance ('ClassName',' instance') to create singleton bindings.
ReflectionException is thrown if the container cannot resolve the dependency, but we can use the App::resolvingAny (Closure) method to parse any specified type in the form of a callback function.
Note: if you have registered a parsing method for a type, the resolvingAny method will still be called, but it will directly return the return value of the bind method.
Thank you for reading! This is the end of this article on "what does dependency injection in laravel refer to?". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.