Benefits of using the Laravel service container

Source: Internet
Author: User
This article mainly introduces the use of Laravel service container advantages, has a certain reference value, now share to everyone, the need for friends can refer to

if the core of the Laravel framework is what, then it is undoubtedly a service container . Understanding the concept of a service container is too important for us to use laravel, and it should be understood that the concept of a service container is an important condition to differentiate whether or not to get started laravel. Because the entire framework is built on the basis of the service container.

Laravel service container is like a highly automated factory where you need something to customize a good model and use a specific interface to make it.

Because the service container is used, most of the objects in Laravel are instantiated in this way:

$obj 1 = $container->make (' Class1 ', ' class2 '); $obj 2 = $container->make (' Class3 ', ' class4 ');

However, without using a service container, the following can be done:

$obj 1 = new Class1 (new Class2 ()), $obj 2 = new Class3 (new Class4 ());

So what is the advantage of using a service container? Let's take a few concrete examples to analyze its advantages:

Example one, sending mail

We encapsulate the ability to send a message into a class that needs to be instantiated and invoked when the sending method is used.
The following are common ways to not use the Laravel service container:

/** * Send mail Service class */class emailservice{public    function Send () {        //todo send mail method    }}//If you want to send a message anywhere, we'll copy the following two lines of code $ Emailservice = new Emailservice (); $emailService->send ();

After using the Laravel service container:

$this->app->bind (' Emailservice ', function ($app) {    return new Emailservice ();}); /If you want to send an email anywhere, we will copy the following two lines of code $emailservice = App (' Emailservice '); $emailService->send ();

This makes our code more concise, and with the help of the middle tier, the flexibility increases (decoupling), so it's more convenient whether it's testing (we can forge classes to replace the Emailservice class in testing) or optimizing the Emailservice class.

You just need to change this place. $this->app->bind (' Emailservice ', function ($app) {    return new Supperemailservice ();});

The other parts of the call we don't have to move at all, and if we don't have this binding operation, we have to make the changes in every place where we use the mail service.

Use every place in the Eamilserice class to change $emailservice = new Supperemailservice (); $emailService->send ();

Example two, the realization of a single case mode

As the above example, for performance reasons, you need to implement a singleton pattern for the Suppereamilservice class, so if you do not use the Laravel service container, you will change the Supperemailservice class as follows:

Class suppereamilservice{      //Create a static private variable save the class object     static private $instance;         Prevent direct creation of object      Private function __construct () {              }         //Prevent clone Object     Private Function __clone () {      }     static Public Function getinstance () {                 ///To determine if $instance is a Uni object                 //not created         if (!self:: $instance instanceof Self) { Self             :: $instance = new self ();         }         Return self:: $instance;              }          Send Message method public     function Send () {             }}

In addition, since the Suppereamilservice class constructor is now private and cannot be instantiated with the new keyword, it should be changed where each instantiation of the Supperemailservice class is:

$emailService =supperemailservice::getinstance (); $emailService->send ();

The Laravel service container is natively supported by a singleton, and the following is how Laravel is implemented:

Just change bind to Singleton $this->app->singleton (' Emailservice ', function ($app) {    return new Supperemailservice ();});

To achieve a single case even only need to change a line of code, the original bind method to change to Singleton, through the container to take out is a single case, it is very convenient.

Example three, the traveler to travel

This example assumes that a traveler travels to Tibet, can make a train (train) or walk (leg).
Do not use the Laravel service container:

<?phpinterface traffictool{public  function Go (); Class Train implements traffictool{public  function Go ()  {  echo "Train ..."}  } Class Leg implements traffictool{public  function Go ()  {  echo "Leg:";  }} Class traveller{  /**  * @var leg|null| Train  * Travel Tools */  protected $_traffictool;  Public function __construct (Traffictool $trafficTool)  {  $this->_traffictool = $trafficTool;  }  Public Function Visittibet ()  {  $this->_traffictool->go ();}  }

When travelers travel by train we usually write:

<?php $train = new Train (), $tra = new Traveller ($train); $tra->visittibet ();

In fact, this is very good, because the dependence on travel tools has been transferred to the outside through the interface. However, there is a dependency when using new to instantiate an object. For example above $tra = new Traveller ($trafficTool), which means we have to have a $traffictool before creating a Traveller, That is, traveller relies on traffictool. When using new to instantiate the traveller, there is a coupling between traveller and traffictool. Thus, the two components cannot be separated.

Now let's see how the Laravel service container is implemented:
Binding classes in the service container

<?phpnamespace App\providers;use Laravel\lumen\providers\eventserviceprovider as ServiceProvider;class Repositoryserviceprovider extends serviceprovider{public  function Register ()  {     //Bind class $this in the service container     - >app->bind (' Traffictool ', ' Train ');     $this->app->bind (' Traveller ', ' Traveller ');}  }

Instantiating an Object

<?php//Instantiate Object $tra = App ()->make (' Traveller '); $tra->visittibet ();

When we use the service container to get the object of the travel class, the container automatically injects the parameters required by the object. And before that I just had to bind a specific class, which was true automation, and made the travel and travel tools completely decoupled. When we need to change the way we travel, we just need to change the bindings.

Summarize

Here are a few simple examples, if you can fully understand and master the Laravel service container, in real development it will provide you with more convenience. Of course, it is not perfect, the next blog intends to describe its shortcomings, in short, the actual use of weaknesses is the key.

The above is the whole content of this article, I hope that everyone's learning has helped, more relevant content please pay attention to topic.alibabacloud.com!

Related Article

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.