Table of Contents
Example 1. Sending emails
Example 2, Implementing the singleton mode
Example 3, Traveler Goes Travel
Summary
Home Backend Development PHP Tutorial Advantages of using Laravel service container

Advantages of using Laravel service container

Jul 06, 2018 pm 01:37 PM
laravel php

This article mainly introduces the advantages of using Laravel service container, which has certain reference value. Now I share it with you. Friends in need can refer to it

If we talk about the core of laravel framework What it is, then it is undoubtedly the service container. Understanding the concept of service containers is very important for us to use laravel. It should be said that understanding the concept of service containers is an important condition for distinguishing whether to get started with laravel. Because the entire framework is built on the basis of service containers.

Advantages of using Laravel service containerThe laravel service container is like a highly automated factory. Whatever you need, customize the model and use specific interfaces to manufacture.

Because the service container is used, the instantiation method of most objects in laravel is like this:

$obj1 = $container->make('class1', 'class2');
$obj2 = $container->make('class3', 'class4');
Copy after login

But without using the service container, the following method can also be done ::

$obj1 = new class1(new class2());
$obj2 = new class3(new class4());
Copy after login

So what are the advantages of using service containers? Let's analyze its advantages through some specific examples:

Example 1. Sending emails

We encapsulate the function of sending emails into a class. When needed, instantiate and call Send method.
The following are common ways not to use laravel service container:

/**
 *发送邮件服务类
 */
class EmailService{
    public function send(){
        //todo 发送邮件方法
    }
}

//如果任何地方要发邮件我们就复制下面这两行代码
$emailService = new EmailService();
$emailService->send();
Copy after login

After using laravel service container:

$this->app->bind('emailService', function ($app) {
    return new EmailService();
});

//如果任何地方要发邮件我们就复制下面这两行代码
$emailService = app('emailService');
$emailService->send();
Copy after login

This makes our code more concise, and because of the middle layer, the flexibility is improved (decoupling), so whether it is testing (we can fake the class to replace the EmailService class during testing) or optimizing the EmailService class, it becomes more convenient.

//只需要改这一个地方
$this->app->bind('emailService', function ($app) {
    return new SupperEmailService();
});
Copy after login

We don’t need to touch the other calling parts at all. If we don’t have this binding operation, we have to make changes in every place where the mail service is used.

//使用到EamilSerice类的每个地方都要更改
$emailService = new SupperEmailService();
$emailService->send();
Copy after login

Example 2, Implementing the singleton mode

Still the above example, for performance reasons, you need the SupperEamilService class to implement the singleton mode, so without using the laravel service container , you change the SupperEmailService class as follows:

class SupperEamilService{
      //创建静态私有的变量保存该类对象
     static private $instance;
   
      //防止直接创建对象
      private function __construct(){
         
     }
         //防止克隆对象
     private function __clone(){
 
     }
     static public function getInstance(){
                 //判断$instance是否是Uni的对象
                 //没有则创建
         if (!self::$instance instanceof self) {
             self::$instance = new self();
         }
         return self::$instance;
         
     }
     
     //发送邮件方法
     public function send(){
        
     }
 }
Copy after login

In addition, since the SupperEamilService class constructor is now private, the object cannot be instantiated through the new keyword, so every place where the SupperEmailService class is instantiated To change it to this:

$emailService=SupperEmailService::getInstance();
$emailService->send();
Copy after login

The laravel service container naturally supports singletons. The following is how laravel implements it:

//只需要把bind改成singleton 
$this->app->singleton('emailService', function ($app) {
    return new SupperEmailService();
});
Copy after login

To implement a singleton, you only need to change one line of code and replace the original bind method. Change it to singleton, and what is taken out through the container is a singleton, which is really convenient.

Example 3, Traveler Goes Travel

This example assumes that a traveler goes to Tibet. He can take the train (train) or walk (leg).
Do not use laravel service container:

<?php

interface 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
  * 旅行工具
  */
  protected $_trafficTool;

  public function __construct(TrafficTool $trafficTool)
  {
  $this->_trafficTool = $trafficTool;
  }

  public function visitTibet()
  {
  $this->_trafficTool->go();
  }
}
Copy after login

When travelers want to travel by train, we usually write like this:

<?php
 $train = new Train();
$tra = new Traveller($train);
$tra->visitTibet();
Copy after login

In fact, this way of writing is already very good, because it is a travel tool The dependencies have been transferred to the outside through interfaces. However, dependencies will still occur when using new to instantiate objects. For example, $tra = new Traveller($trafficTool) above, which means that we must have a $trafficTool before creating a Traveller, that is, Traveler depends on trafficTool. When using new When instantiating Traveller, there is coupling between Traveller and trafficTool. In this way, these two components cannot be separated.

Now let’s take a look at how to use the laravel service container:
Binding classes in the service container

<?php
namespace App\Providers;

use Laravel\Lumen\Providers\EventServiceProvider as ServiceProvider;

class RepositoryServiceProvider extends ServiceProvider
{
  public function register()
  {
     //在服务容器中绑定类
     $this->app->bind( &#39;TrafficTool&#39;, &#39;Train&#39;);
     $this->app->bind(&#39;Traveller&#39;, &#39;Traveller&#39;);
  }
}
Copy after login

Instancing objects

<?php
// 实例化对象
$tra = app()->make(&#39;Traveller&#39;);
$tra->visitTibet();
Copy after login

When we use When the service container obtains the travel class object, the container will automatically inject the parameters required by the object. Before that, I only needed to bind specific classes. This reflected true automation and completely decoupled the travel class and travel tool class. When we need to change the way we travel, we just need to change the binding.

Summary

A few simple examples are given above. If you can fully understand and master the laravel service container, it will provide you with more convenience in actual development. Of course, it is not perfect, and I will describe its shortcomings in the next blog. In short, the key is to maximize strengths and avoid weaknesses in actual use.

The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

Using Docker compose to orchestrate Laravel applications

Initial installation of Laravel

The above is the detailed content of Advantages of using Laravel service container. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

In Laravel, how to deal with the situation where verification codes are failed to be sent by email? In Laravel, how to deal with the situation where verification codes are failed to be sent by email? Mar 31, 2025 pm 11:48 PM

The method of handling Laravel's email failure to send verification code is to use Laravel...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

How to implement the custom table function of clicking to add data in dcat admin? How to implement the custom table function of clicking to add data in dcat admin? Apr 01, 2025 am 07:09 AM

How to implement the table function of custom click to add data in dcatadmin (laravel-admin) When using dcat...

See all articles