5

義務を遂行するために別のオブジェクトに依存するいくつかのメソッドを持つクラスがあるとします。違いは、それらはすべて同じクラスのオブジェクトに依存していますが、クラスの異なるインスタンスが必要です。より具体的には、メソッドは依存関係の状態を変更するため、各メソッドにはクラスのクリーンなインスタンスが必要です。

これは私が考えていた簡単な例です。

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';
    }
}

これにより、オブジェクトの 1 つのインスタンスを正しい状態で取得でき、別のインスタンスが必要な場合はそれをコピーするだけで済みます。これが理にかなっているのか、それとも、依存性注入とコードをテスト可能に保つことに関する基本的なガイドラインを見過ごしているのか、私はただ興味があります.

4

3 に答える 3

4

これには Factory パターンを使用します。

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) 
    ...
于 2013-07-25T03:21:14.250 に答える