2015-04-02 66 views
1

我有一個類(可以稱之爲TestClassA),其中構造看起來像這樣注入任何四類成爲階級

public function __constructor(SomeInterface $some, AnotherInterface $another, $additionalArgs = null) 
{ 
    // Rest of code 
} 

$additionalArgs值可以來自任何的四個獨特的類。根據用戶的條件設置,這些類中的每一個都會爲上面的類添加唯一的查詢參數。讓我們命名這些類

  • TESTB

  • TESTC

  • TESTD

  • TESTE

我不知道,如果接口注入將是我最好的解決辦法在這裏,一旦一個條件被設定,它就會變成mos t可能永遠不會再改變,並且在任何給定時間只能設置一個選項。例如,如果用戶決定使用類別,則他將改變爲其餘三個類別中的任一類別的概率幾乎爲零。所以,如果我是正確的,如果我使用接口注入(如在下面的例子),並添加所有四班,我將實例3班不必要的,因爲他們將在最可能不會習慣

public function __constructor(
    SomeInterface $some, 
    AnotherInterface $another, 
    TestBInterface $testB, 
    TestCInterface $testC, 
    TestDInterface $testD, 
    TestEInterface $testE 
) { 
    // Rest of code 
} 

我想到的是創建我的TestClassA$additionalArgs屬性,創建所需的類的新實例,可以說TestC,然後將其傳遞到$additionalArgs,然後我在一個方法中使用獲得所需的值。

$a = new SomeClass; 
$b = new AnotherClass; 
$c = new TestC; 

$d = new TestClassA($a, $b, $c->someMethod()); 

我的問題是,我該如何確保傳遞給$additionalArgs值應該傳遞到這個參數四大類之一的有效實例。我已經嘗試在我的方法中使用instanceof進行驗證,在本示例中爲someMethod(),但條件失敗

有關如何解決此問題並仍「遵守」基本OOP原則的任何建議?

+0

它失敗的原因是因爲你傳遞的是函數的結果而不是對象本身。除非你傳入對象,否則你不能驗證它來自這四個類中的一個。 – Styphon 2015-04-02 07:54:03

+0

所以你的意思是,我應該把'$ c'傳遞給'$ additionalArgs',然後在'TestClassA'檢查中從哪裏來的輸入,如果它是我的四個類中的一個的有效實例。如果是,請以答案的形式回答(如果您願意,可以添加一個小例子),以便我可以接受。我忘記在我的問題中提到這也是我考慮過的事情。恨我的問題沒有回答:-) – 2015-04-02 08:12:07

回答

1

當前您傳遞的是方法的結果,您無法測試它以查看它來自哪個類,因此instanceof將不起作用。你需要做的是傳入對象,測試並調用方法。試試這個:

class TestClassA() { 
    $foo; 
    $bar; 
    $testB; 
    $testC; 
    $testD; 
    $testE; 
    public function __constructor(Foo $foo, Bar $bar, $test = null) 
    { 
     $this->foo = $foo; 
     $this->bar = $bar; 
     if (! is_null($test)) 
     { 
      if ($test instanceof TestClassB) 
      { 
       $this->testB = $test->someMethod(); 
      } 
      elseif ($test instanceof TestClassC) 
      { 
       $this->testC = $test->someMethod(); 
      } 
      elseif ($test instanceof TestClassD) 
      { 
       $this->testD = $test->someMethod(); 
      } 
      elseif ($test instanceof TestClassE) 
      { 
       $this->testE = $test->someMethod(); 
      } 
      // Optional else to cover an invalid value in $test 
      else 
      { 
       throw new Exception('Invalid value in $test'); 
      } 
     } 
     // Rest of code 
    } 
} 

$a = new Foo; 
$b = new Bar; 
$c = new TestClassC; 

$d = new TestClassA($a, $b, $c); 
+0

正是我想要的。謝謝。請享用 :-) – 2015-04-02 08:30:23