max*_*ool 5 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';
    }
}
这使我能够以正确的状态获得对象的一个实例,如果需要另一个实例,则可以复制它。我只是好奇这是否有意义,或者是否正在寻找有关依赖项注入并保持代码可测试的基本指南。
我会为此使用工厂模式:
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 DependencyFactoryInterface
{
    public function create();
}
class DependencyFactory implements DependencyFactoryInterface
{
    // ...
}
class Something {
    public function __construct(DependencyFactoryInterface $factory) 
    ...