For example, I created a new directory Services in the APP directory, and placed a service EmailService.php in it. When I want to call it in other controllers, I can directly quote:
use App\Services\EmailService;
This way you can use it normally.
Then the question is:
1. It can be used normally as above, so under what circumstances should this service
be placed in the service provider
Go inside? The relationship between
2, service provider
, and service container
has never been clear. Is service
placed in service container#? ##Inside or
Service Provider?
Service Provider and
Service ContainerWhat are their respective responsibilities?
in
服务提供者
把服务
放进服务容器
.An additional introduction to dependency injection containers: Learn to Stop Wiring and Love Laravel's Container
The questioner will ask this question. I guess the questioner still doesn’t know much about dependency injection and laravel’s service container. (Of course, I don’t understand it very well. The following is just my simple understanding)
If you directly specify a class under a certain namespace inside your controller (this class should be an implementation of an interface (contract)), then this class will be coupled with the controller. When you want to modify this implementation class, you need to modify the controller and the methods called in the controller.
If you write it in the service provider, firstly, it can be decoupled (the parameters of the controller method are injected into the service implementation class through type hints), and secondly, if the service also depends on other services, laravel's service The container handles these dependencies automatically. Instead of using a bunch of use syntax in front of the controller to import these dependent libraries yourself. The third is to constrain the service through the interface to only provide the methods it should provide (single responsibility).
Basic understanding, please point out in the comment area if there are any mistakes.
Service container and service provider are two different things, without any mandatory relationship, so I will talk about them separately below.
Service container:
is a global associative array variable, which stores things in it, and then the object can be retrieved by name anywhere.
Service provider:
In each service provider, there is a piece of initialization code that will be used by the entire program, such as
We can see from the above example that we always have to write these initialization codes. It's just that Laravel defines it as a specification, forcing you to classify and store the initialization code. (You can still put different types of initialization code all in
app/Providers/AppServiceProvider.php
)Please correct me.