Home  >  Article  >  Backend Development  >  Laravel中“服务提供者”和“服务容器”的关系是什么?

Laravel中“服务提供者”和“服务容器”的关系是什么?

WBOY
WBOYOriginal
2016-06-06 20:16:491227browse

Laravel中“服务提供者”和“服务容器”的关系是什么?

回复内容:

Laravel中“服务提供者”和“服务容器”的关系是什么?

container是所有service的载体,provider的作用是提供注册service到container的方法。

这其实应该说是三者之间的关系。

这两天刚好再看,同作为菜鸟来说下自己的理解;
laravel的服务提供概念,是用了php的依赖注入,依赖注入的实现用了反射机制
1.首先把需要的B类的实例化对象放到一个匿名函数中,然后再把此类和匿名函数放到容器中,假设容器是一个数组
2.假设A类的执行依赖B类,那么在A类的构造方法参数中,指定参数的类型是B类型
3.执行A类时,通过反射,知道A类依赖B类,那么就从容器中执行B类对应的匿名函数,得到一个实例化对象,传给A继续执行

服务提供者就是用来注册,存放将来需要的类到容器中。
服务容器的作用就是存放需要的类,再某个地方用到时,就从容器中获取。

这些作用就是减少模块间的依赖关系。在用到时,自动加进去。

参考:https://www.insp.top/article/learn-laravel-container

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