How to Use the boot and providers methods of laravel ServiceProvider

Source: Internet
Author: User
Can you give an example? The document does not seem very detailed. For me who just understood the concept of IOC and DI, I barely had to understand what the register method is doing. Can someone help me explain it? Can you give an example? The document does not seem to be detailed.
Just understood IOCAnd DII can barely understand the concept. registerWhat is the method doing?
Can someone explain this?

Reply content:

Can you give an example? The document does not seem to be detailed.
Just understoodIOCAndDII can barely understand the concept.registerWhat is the method doing?
Can someone explain this?

If youIoCAndDIFor more information, see the following link. We recommend that you read the information in the following order:

1. The description of Service Container and Service Provider in Laravel official documents is preliminarily understood based on the accumulated experience.

2. An image of IoC Overview

3. Use simple PHP code to describe IoC

4. Detailed description of IoC usage and Classification

Finally, let's look back at the Service iner and Service Provider documents and view the user Request Lifecycle Overview: Request Lifecycle, which can be clearly understood.

Now we haveIoCAndLaravelBasic understanding of the Request LifecycleServiceProviderIt will not be too difficult.

ServiceProvider

Classes inherited from ServiceProvider generally rewrite two important functions: the register and boot methods.

0x0. whimsy

One day I suddenly wanted to use Laravel to implement a program and input a question to get the answer List link on SegmentFault. I would like to talk about the code below:

class SegmentFault {    private $server;    public function __construct($server)    {        $this->server = $server;    }        /**    * Retrieve the answers    */    public function answer($question)    {        return  $this->server . $question;    }}

Return to Controller and call the SegmentFault class. Do you need to instantiate it manually? No, Laravel will automatically instantiate it for you:

public function index(SegmentFault $segmentFault) {    return $segmentFault->answer('What is Service Provider in Laravel ?');  }

It seems that my treasure is not old, and the beautiful Laravel framework is completed in minutes. I'm so excited that I can refresh the page:

Chen Bu Mu Cao, reported an error. The error message is obviously that the SegmentFault parameter cannot be parsed. What about automatic dependency injection !?

No, I need to input the search Link parameter of SegmentFault (otherwise, how can Laravel know the parameter to be constructed), but this requires manual instantiation .. Do not pass a parameter:

public function index() {    $segmentFault = new SegmentFault('https://segmentfault.com/search?q=');    return $segmentFault->answer('What is Service Provider in Laravel ?');  }

This is okay.

0x1. Start laziness

Now I want to provide this function on other pages. It seems that it is a little troublesome to instantiate it every time. If SegmentFault changes the domain name one day, it is necessary to modify more than a dozen functions ......

Think about this serious result and have to improve this program. Okay. Let's look back at IoC. Since SegmentFault class is instantiatedParameters need to be inputTo search for documents, it was quite simple. First, create a ServiceProvider to learn:

class SegmentFaultServiceProvider extends ServiceProvider {    public function register() {        $this->app->bind(SegmentFault::class, function() {            return new SegmentFault('https://segmentfault.com/search?q=');        });    }}

In this way, the dependency information is configured. Laravel knows how to correctly instantiate this class and rewrite the program:

public function index(SegmentFault $segmentFault) {    return $segmentFault->answer('What is Service Provider in Laravel ?');}

Why !? By the way, you also need to register this Provider in config/app. php:

'providers' => [    // ...    App\Providers\SegmentFaultServiceProvider::class,]

Refresh again. Now it can work normally, So cool !! I couldn't help jumping up from the chair.

0x2. Summary

IoC assigns internally designed classes to the system for control. However, some classes require specific parameters during initialization, or when you need to bind implementation classes to an interface, in this case, you must configure these dependencies so that the system can correctly parse and reference them.

Register

Register is like this. You can configure class dependencies in register, bind implementation classes to interfaces, and set class aliases.

Boot

The boot method is called after the register method, which means that you do not have to worry that it is not bound or instantiated when an instance is injected.

For example, you have created two classes: SegmentFault and SegmentFaultApi. The former depends on the latter, but in register, you are not sure that the class is instantiated first. Then you can reference the latter in boot, because both classes have been correctly configured.

Providers

The providers method is used to delay the loading of ServiceProvider. For example, if you want to let the system parse the class when referencing, you can set the $ defer variable to true to delay the startup, saving the cost:

protected $defer = true;

When delayed startup is set, you need to override the providers function. When Laravel encounters a delayed loading class, you can call the correct register function to parse the class by searching for the specified reference keyword in the providers function of each ServiceProvider:

public function providers() {    return [SegmentFault::class];}

This is my article: PHP Laravel processes a request. (Of course, because the time relationship has not been completed, it is to be continued for 23333

If something is wrong, I hope Daniel can correct it. Thx ~

Above.

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.