Home  >  Article  >  Backend Development  >  Regarding the use of laravel containers, under what circumstances do you use them?

Regarding the use of laravel containers, under what circumstances do you use them?

WBOY
WBOYOriginal
2016-10-10 11:56:121438browse

I don’t have a good understanding of laravel containers yet.
My understanding is that there are many objects that can be called in the container.
You can use it directly when needed, no need for new etc.

I would like to ask, will everyone use this feature?
How do you generally use this feature in projects? Should we separate out a service layer and put each service into a container?
Call in controller?
Or just don’t use it?

Reply content:

I don’t have a good understanding of laravel containers yet.
My understanding is that there are many objects that can be called in the container.
You can use it directly when needed, no need for new etc.

I would like to ask, will everyone use this feature?
How to use this feature in projects? Should we separate out a service layer and put each service into a container?
Call in controller?
Or just don’t use it?

The Laravel container is a place where services are placed. These services are instance objects or closures bound to the container one by one. There are three main binding methods: bind(), singleton() and instance(). How to resolve Service from the container: make(), these are all in IlluminateContainerContainer, and IlluminateFoundationApplication extends Container.

Regarding how Container works, when you use Constructor Injection or Method Injection in Controller, you are already using Container, because Container will automatically parse these services for you, such as:

<code>class AccountController extends Controller
{
    // 这里是Method Injection,Container会自动解析出Request,而不需要去new Request获得对象
    // 从容器中解析服务是用的Container::make()方法
    public function test(Request $request) 
    {
        return $request->ip();
    }
}</code>

So container services have always been used. In general, containers are places where service construction is separated. Traditionally, the required services are constructed within the dependent object, but now the required dependencies are constructed within the container, and it is Automatically, and automatically injected into the dependent object, thus achieving decoupling.

For the source code analysis of Container and Application, you can see:
Laravel study notes - Container source code analysis
Laravel study notes - IoC Container instantiation source code analysis

Statement:
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