You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如下控制器代码是否为依赖注入示例?如何优化其写法?

问题解答

1. 代码是否属于依赖注入?

不属于。
依赖注入的核心原则是类自身不负责实例化它的依赖对象,依赖要从外部传入。你给出的代码中,ExampleController直接在方法内部硬编码实例化了AnotherController,相当于把两个类强绑定在一起,既不便于单元测试(无法 mock AnotherController 的返回),也不便于后续替换依赖实现,完全不符合依赖注入的设计要求。

2. 最优改写方案

最推荐使用构造函数注入的方式改造,这是PHP开发通用规范中优先推荐的依赖注入实现方式,兼容性和可维护性最好:

class ExampleController
{
    // 声明依赖的类属性
    protected AnotherController $anotherController;
    
    // 通过构造函数把依赖从外部传入
    public function __construct(AnotherController $anotherController)
    {
        $this->anotherController = $anotherController;
    }

    public function testOne()
    {
        $newTestMethod = $this->anotherController->testTwo();
    }
}

改造后的优势:

  • 两个类的耦合度大幅降低,ExampleController不再关心AnotherController的实例化逻辑,实例化工作统一交给依赖注入容器处理
  • 单元测试时可以轻松传入AnotherController的mock对象,无需耦合真实的业务逻辑
  • 如果后续需要替换AnotherController的实现,只要传入符合相同接口的对象即可,无需修改ExampleController内部的代码

内容的提问来源于stack exchange,提问作者Mohsen Movahed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 10:27:03