php - 克隆依赖项的副本(依赖注入(inject))是否有意义?

标签 php oop dependency-injection

假设我有一个类,其中有一些方法依赖于另一个对象来执行它们的职责。不同之处在于它们都依赖于同一类对象,但需要该类的不同实例。或者更具体地说,每个方法都需要一个干净的类实例,因为这些方法将修改依赖项的状态。

这是我想到的一个简单示例。

class Dependency {
    public $Property;
}


class Something {
    public function doSomething() {
        // Do stuff
        $dep = new Dependency();
        $dep->Property = 'blah';
    }

    public function doSomethingElse() {
       // Do different stuff
       $dep = new Dependency(); 
       $dep->Property = 'blah blah';
    }
}

技术上我可以做到这一点。

class Something {
    public function doSomething(Dependency $dep = null) {
        $dep = $dep && is_null($dep->Property) ? $dep : new Dependency();
        $dep->Property = 'blah';
    }

    public function doSomethingElse(Dependency $dep = null) {
       $dep = $dep && is_null($dep->Property) ? $dep : new Dependency();
       $dep->Property = 'blah blah';
    }
}

我的问题是我必须经常检查传入的依赖对象是否处于正确状态。新创建的状态。所以我只想做这样的事情。

class Something {
    protected $DepObj;

    public function __construct(Dependency $dep) {
        $this->DepObj = $dep && is_null($dep->Property) ? $dep : new Dependency();
    }
    public function doSomething() {
        // Do stuff
        $dep = clone $this->DepObj;
        $dep->Property = 'blah';
    }

    public function doSomethingElse() {
       // Do different stuff
       $dep = clone $this->DepObj;
       $dep->Property = 'blah blah';
    }
}

这使我能够获得处于正确状态的对象的一个​​实例,如果我需要另一个实例,我可以直接复制它。我只是好奇这是否有意义,或者我是否忽略了关于依赖注入(inject)和保持代码可测试的基本指南。

最佳答案

我会为此使用工厂模式:

class Dependency {
    public $Property;
}

class DependencyFactory
{
    public function create() { return new Dependency; }
}

class Something {
    protected $dependencies;

    public function __construct(DependencyFactory $factory) {
        $this->dependencies = $factory;
    }

    public function doSomething() {
       // Do different stuff
       $dep = $this->dependencies->create();
       $dep->Property = 'Blah';
    }

    public function doSomethingElse() {
       // Do different stuff
       $dep = $this->dependencies->create();
       $dep->Property = 'blah blah';
    }
}

您可以通过引入接口(interface)进一步解耦工厂:

interface DependencyFactoryInterface
{
    public function create();
}

class DependencyFactory implements DependencyFactoryInterface
{
    // ...
}

class Something {
    public function __construct(DependencyFactoryInterface $factory) 
    ...

关于php - 克隆依赖项的副本(依赖注入(inject))是否有意义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17847758/

相关文章:

c# - ASP.NET Core 2.0 依赖注入(inject)默认实例

php - 使用 Zend Framework 进行文件上传和单元测试

php - 如何在 codeigniter xampp 窗口中从本地主机发送电子邮件

c# - 接口(interface)、类实现和新方法

c# - 公共(public)实例变量访问错误: "An object reference is required for the non-static field, method, or property..."

java - 是否可以使用从同一个类生成的bean

php - 无法使用 PHP 和 session 变量从 SQL 数据库检索数据

php - 从datetime=now()显示mysql中的数据库

C++ 类设计——如何在基类析构函数中清理

java - Spring中如何构造Map<String, List<String>>数据结构