💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
## 依赖注入 # 了解依赖注入 *依赖注入*和*依赖注入容器*是不同的东西: * **依赖注入是一种**编写更好代码的方法 * **容器是**帮助注入依赖项的工具 您*不需要*容器来进行依赖注入。但是,容器可以帮助您。 PHP-DI 就是这样:使依赖注入更实用。 ## 理论[#](https://php-di.org/doc/understanding-di.html#the-theory) ### 经典的 PHP 代码[#](https://php-di.org/doc/understanding-di.html#classic-php-code) 以下是**不**使用 DI 的代码大致如何工作: * 应用程序需要 Foo(例如控制器),所以: * 应用程序创建 Foo * 应用程序调用 Foo * Foo 需要 Bar(例如服务),所以: * Foo 创建 Bar * Foo 呼叫 Bar * Bar 需要 Bim(服务、存储库……),所以: * Bar 创建 Bim * 酒吧做点什么 ### 使用依赖注入[#](https://php-di.org/doc/understanding-di.html#using-dependency-injection) 以下是使用 DI 的代码大致如何工作: * 应用需要Foo,需要Bar,需要Bim,所以: * 应用程序创建 Bim * 应用程序创建 Bar 并为其提供 Bim * 应用程序创建 Foo 并给它 Bar * 应用程序调用 Foo * Foo 呼叫 Bar * 酒吧做点什么 这就是**控制反转**的模式。依赖关系的控制从一个被调用**反**转到一个调用。 https://php-di.org/doc/understanding-di.html [依赖自动注入 - webman](https://www.workerman.net/doc/webman/di.html#%E4%BE%9D%E8%B5%96%E8%87%AA%E5%8A%A8%E6%B3%A8%E5%85%A5)