Advantages of using Laravel service container
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.
The 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');
But without using the service container, the following method can also be done ::
$obj1 = new class1(new class2()); $obj2 = new class3(new class4());
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();
After using laravel service container:
$this->app->bind('emailService', function ($app) { return new EmailService(); }); //如果任何地方要发邮件我们就复制下面这两行代码 $emailService = app('emailService'); $emailService->send();
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(); });
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();
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(){ } }
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();
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(); });
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(); } }
When travelers want to travel by train, we usually write like this:
<?php $train = new Train(); $tra = new Traveller($train); $tra->visitTibet();
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( 'TrafficTool', 'Train'); $this->app->bind('Traveller', 'Traveller'); } }
Instancing objects
<?php // 实例化对象 $tra = app()->make('Traveller'); $tra->visitTibet();
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

Laravel provides a comprehensive Auth framework for implementing user login functions, including: Defining user models (Eloquent model), creating login forms (Blade template engine), writing login controllers (inheriting Auth\LoginController), verifying login requests (Auth::attempt) Redirecting after login is successful (redirect) considering security factors: hash passwords, anti-CSRF protection, rate limiting and security headers. In addition, the Auth framework also provides functions such as resetting passwords, registering and verifying emails. For details, please refer to the Laravel documentation: https://laravel.com/doc

When developing websites using CraftCMS, you often encounter resource file caching problems, especially when you frequently update CSS and JavaScript files, old versions of files may still be cached by the browser, causing users to not see the latest changes in time. This problem not only affects the user experience, but also increases the difficulty of development and debugging. Recently, I encountered similar troubles in my project, and after some exploration, I found the plugin wiejeben/craft-laravel-mix, which perfectly solved my caching problem.

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

In the Laravel framework version selection guide for beginners, this article dives into the version differences of Laravel, designed to assist beginners in making informed choices among many versions. We will focus on the key features of each release, compare their pros and cons, and provide useful advice to help beginners choose the most suitable version of Laravel based on their skill level and project requirements. For beginners, choosing a suitable version of Laravel is crucial because it can significantly impact their learning curve and overall development experience.

Want to learn the Laravel framework, but suffer from no resources or economic pressure? This article provides you with free learning of Laravel, teaching you how to use resources such as online platforms, documents and community forums to lay a solid foundation for your PHP development journey from getting started to master.

The Laravel framework has built-in methods to easily view its version number to meet the different needs of developers. This article will explore these methods, including using the Composer command line tool, accessing .env files, or obtaining version information through PHP code. These methods are essential for maintaining and managing versioning of Laravel applications.
