【问题标题】:PHP Setter dependency with "default dependencies"具有“默认依赖项”的 PHP Setter 依赖项
【发布时间】:2016-02-02 00:24:08
【问题描述】:

我目前正在开发一个依赖注入容器,我遇到了很多不同类型的容器(Pimple、Orno/di、Laravel 的......),我计划做一些接近 Pimple 的事情。但是我仍然有一个问题,如果我使用 setter 和 getter 进行 DI,在依赖类的构造函数中注入“默认依赖项”是否正确?让我举个例子:

这是我的示例代码:

<?php

class Dependency
{
    public function print($str)
    {
        echo $str;
    }
}


class Dependent
{
    private $_dependency;

    public function __construct()
    {
        $this->_dependency = new Dependency;
    }


    public function setDependency(Dependency $dep)
    {
        $this->_dependency = $dep;
        return $this;
    }

    public function depPrint($str)
    {
        $this->_dependency->print($str);
        return $this;
    }
}

这样,用户代码可以直接使用类而不知道它的依赖关系:

$instance = new Dependent;
$instance->depPrint('Hello world');

或者如果用户代码需要该类使用另一个依赖项,它可以这样做:

$instance = new Dependent;
$instance->setDependency(new Dependency)
    ->depPrint('Hello world');

我觉得它很方便,因为在测试中您可以用模拟类替换依赖项,并且用户代码不必了解类依赖项的任何信息。我发现最大的缺点是它仍然会与默认依赖项建立耦合,但这可以通过检查类是否存在来轻松解决,如果它不存在,则默认情况下不要注入任何东西。那么,这个系统有什么缺点,我应该使用它还是应该使用其他东西?

提前谢谢你。

【问题讨论】:

    标签: php dependency-injection containers


    【解决方案1】:

    你可以把这两件事结合起来:

    public function __construct($dep = null)
    {
        if (is_null($dep)) {
          $this->_dependency = new Dependency;
        } else {
          $this->_dependency = $dep;
        }
    }
    

    【讨论】:

    • 我看到有人说“构造函数的参数不应该是可选的”,我不知道这是不是真的,但无论如何你的选择很有趣,我会看看我是否可以有效地将它应用到我的真实代码。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2014-08-27
    • 1970-01-01
    • 2014-03-18
    • 1970-01-01
    • 2012-11-27
    • 1970-01-01
    • 1970-01-01
    • 2014-08-20
    相关资源
    最近更新 更多