Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/293.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP Setter依赖项,带有;“默认依赖项”;_Php_Dependency Injection_Containers - Fatal编程技术网

PHP Setter依赖项,带有;“默认依赖项”;

PHP Setter依赖项,带有;“默认依赖项”;,php,dependency-injection,containers,Php,Dependency Injection,Containers,我目前正在开发一个依赖注入容器,我遇到了很多不同类型的容器(Pimple、Orno/di、Laravel…),我计划做一些类似Pimple的事情。但我仍然有一个问题,如果我使用setter和getter进行DI,在依赖类的构造函数中注入“默认依赖项”是否正确?让我举个例子: 下面是我的示例代码: <?php class Dependency { public function print($str) { echo $str; } } class

我目前正在开发一个依赖注入容器,我遇到了很多不同类型的容器(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->setDependency(new Dependency)
    ->depPrint('Hello world');
我觉得这很方便,因为在测试中,您可以用模拟类替换依赖项,并且用户代码不必知道任何关于类依赖项的信息。我发现最大的缺点是它仍然会创建与默认依赖项的耦合,但这可以通过检查类是否存在来轻松解决,如果不存在,则默认情况下不注入任何内容。那么,这个系统有什么缺点吗?我应该使用它还是使用其他东西


提前谢谢。

您可以将这两件事结合起来:

public function __construct($dep = null)
{
    if (is_null($dep)) {
      $this->_dependency = new Dependency;
    } else {
      $this->_dependency = $dep;
    }
}
我看到一些人说“构造函数的参数不应该是可选的”,我不知道这是不是真的,但不管怎样,你的选择很有趣,我会看看我是否能有效地将它应用到我的实际代码中。非常感谢。
public function __construct($dep = null)
{
    if (is_null($dep)) {
      $this->_dependency = new Dependency;
    } else {
      $this->_dependency = $dep;
    }
}