【问题标题】:Is this an example of dependency injection?这是依赖注入的一个例子吗?
【发布时间】:2021-09-12 18:49:06
【问题描述】:

考虑以下示例:

class ExampleController
{
    public function testOne()
    {
        $newTestMethod = (new AnotherController)->testTwo();
    }
}

正如我们在上面的示例中看到的,我从另一个控制器中的一个控制器获取了新实例。
这段代码是依赖注入的示例吗?
如果答案是肯定的,那么您建议用什么方式来优化编写上述代码?

【问题讨论】:

  • 没有。这里没有注入。事实上,这是一个硬依赖,因为您将两个控制器绑定在一起。

标签: php dependency-injection coding-style


【解决方案1】:

不,不是。依赖注入只不过是显式注入依赖。有a look here

您的代码可能如下所示:

class ExampleController
{
    public function testOne(AnotherController $anotherController)
    {
        $newTestMethod = $anotherController->testTwo();
    }
}

这里你必须真正注入依赖才能使用testOne(),参数是显式且可重用的。

【讨论】:

    猜你喜欢
    • 2019-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-11
    • 2018-09-30
    • 2015-02-27
    相关资源
    最近更新 更多