From apprentice to Artisan translation 01

Source: Internet
Author: User

Dependency Injection

Dependency Injection

The problem

Problems encountered

The foundation of the Laravel framework is its powerful IoC container. To truly understand the framework, a strong grasp of the container are necessary. However, we shold note that an IoC container are simply a convenience mechanism for achieving a software design Pattern:de Pendency injectionl. A container is not necessary to perform dependency injection, it simply makes the task easier.

The foundation of the Laravel framework is a powerful control inversion container (IoC container). In order to truly understand this framework, it is necessary to master the container well. However, we need to understand that the control reversal container is just a tool for facilitating "dependency injection". But to implement dependency injection does not necessarily require controlling the reversal container, it is easier and easier to use the container.


First, let's explore why dependency injection is beneficial. Consider the following class and method:

First, let's look at what benefits he can bring to us for and to use dependency injection. Consider the following code:

Class Usercontroller extends basecontroller{public    function GetIndex ()    {        $users = User::all ();        Return View::make (' Users.index ', compact (' users ');}    }




While the This code is concise, we were unable to test it without hitting an actual database. In other words, the eloquent ORM was tightly coupled to out controller. We have no-to-use or test-this controller without also using the entire eloquent ORM, including hitting a live databas E. This code also violates a software design principle commonly called separation of concerns. Simple Put:our controller knows too much. Controllers does not need to know where the data comes from, and only how to access it. The controller doesn ' t need to know that the data was available in MySQL, and only that it was available somewhere.

This code is very brief, but if we want to test this code, we will definitely have a connection with the actual database. In other words, eloquent ORM (translator Note: Laravel database object Model Library) and the controller is tightly coupled. If you do not use eloquent ORM and do not connect to the actual database, we will not be able to run or test this code. This code also violates the "focus on separation" of the software design principles. Simply put: This controller knows too much. The controller does not need to know where the data is coming from, as long as it knows how to access it. The controller does not need to know where the data is from MySQL or where it comes from, just know that the data is currently available.


Separation of concerns

Focus on separation

Every class should has a single responsibility, and so responsibility should be entirely
Encapsulated by the class.
Each class should have a separate responsibility, and that responsibility should be fully encapsulated by this class. (The Translator notes: I think that is not to let multiple classes responsible for the same duties)


So, it'll be beneficial-us to decouple our web layer (Controller) from our data access layer completely. This would allow us to migrate storage implementations easily, as well as make our code easier to test. Think of the "Web" as just a transport layer into your "real" application.

The benefit of focusing on separation is the ability to decouple Web controllers from data access. This makes it easier to implement storage migrations and easier to test. The "Web" is simply a transfer of data for your real application.


Imagine that your application are like a monitor with a variety of cable ports. You can access the monitor ' s functionality via HDMI, VGA, or DVI. Think of the Internet as just a cable into your application. The bulk of a monitor ' s functionality is independent of the cable. The cable is just a transport mechanism just like HTTP was a transport mechanism for your application. So, we don ' t want to clutter up our transport mechanism (the controller) with application logic. This would allow any transport layer, such as a API or mobile application, to access our application logic.

Imagine you have a monitor-like program with a lot of cable interfaces (HDMI,VGA,DVI, etc.). You can access different monitors through different interfaces. Think of the Internet as another plug-in to your program's cable interface. Most display functions are independent of the cable interface. The cable interface is just a transport mechanism like HTTP is a transmission mechanism for your program. So we don't want to mix the transport mechanism (Controller) with the business logic. The benefit is that many other transport mechanisms, such as API calls, mobile applications, and so on, can access our business logic.


So, instead of coupling we controller to the eloquent ORM, let ' s inject a repository class.

Then let's stop coupling the controller with the eloquent ORM. Let's inject a database class.


Build A contract Set up conventions

First, we ll define an interface and a corresponding implementation:

First we define an interface and then implement that interface.

Interface userrepositoryinterface{public    function All ();}  Class Dbuserrepository implements userrepositoryinterface{public    function All ()    {        return User::all ()- >toarray ();    }}



Next, we'll inject an implementation of the This interface to our controller:

Then we inject the implementation of the interface into our controller.


Class Usercontroller extends basecontroller{public    function __construct (userrepositoryinterface $users)    {        $this->users = $users;    }      Public Function GetIndex ()    {        $users = $this->users->all ();        Return View::make (' Users.index ', compact (' users ');}    }




Now we controller is completely ignorant of where we user data is being stored. Ignorance is bless! Our data could is coming from MySQL, MongoDB, or Redis. Our controllers doesn ' t know the difference, nor should it care. Just by making this small change, we can test our web layer independent of our data layer, as well as easily switch our St Orage implementation.

Now our controller is completely irrelevant to the data plane. It is a blessing to be ignorant here! Our data may be from Mysql,mongodb or Redis. Our controllers do not know or need to know the difference between them. With just such a small change, we can test the Web layer independently of the data layer, and it will be easy to switch the storage implementation in the future.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.