为什么在此示例中使用依赖注入?

时间:2015-10-09 22:15:54

标签: php model-view-controller dependency-injection

请考虑以下代码:

class CategoryController
{
    private $model;

    public function __construct()
    {
        $this->model = new CategoryModel();
    }
}

您将看到Controller依赖于模型。我听说这样做是不可取的,应该注入模型。

我质疑为什么。在我的情况下,我专门针对CategoryModel构建了CategoryController,并且我没有在课堂上看到这样的问题。我的意思是,无论如何,我无法注入那些不兼容的SomeOtherModel ......或者我可以吗?

使用依赖注入代替将其注入Controller似乎浪费代码。

因此,有没有理由在这里使用DI?

2 个答案:

答案 0 :(得分:1)

答案

实际上在那个例子中,最大的问题是什么呢?!没有任何方法只是一个对象持有者没有任何方法得到它!?

是的,我知道,这仅仅是一个例子,但问题就是这个问题,在那个例子中你不需要DI,实际上你根本不需要这个课程!

@Mark Ba​​ker说,如果没有DI / IoC,你就不能轻易测试,因为它已经被严格扫描了。如果你花一些时间来阅读有关测试的内容,对于这种情况也需要Mockery

额外

  

使用依赖注入代替将其注入Controller似乎浪费代码。

如果您没有为您做过DI的事情,那么很容易让对象从构造函数传递或制作默认对象,在您的示例中将是:     使用CategoryModelInterface;

class CategoryController
{
    private $model;

    public function __construct(CategoryModelInterface $categoty = null)
    {
        $this->model = $category
            ? $category
            : new CategoryModel();
    }
}

通过这种方式,您不会浪费太多时间,而且如果/可能/您可能会进行一些测试,或者将模型完全更改为另一个,那么实际上可以做到这一点。

答案 1 :(得分:0)

我认为你不需要DI。但是Mark Baker's comment关于测试是有效的。但是你可以通过对模型使用getter方法来解决这个问题。然后可以在测试中模拟该方法:

class CategoryController
{
    private $model;

    public function __construct()
    {
        ...
    }

    public function getModel() {
        if(!$this->model) {
            $this->model = new CategoryModel();
        }
        return $this->model;
    }
}
相关问题