2014-11-25 42 views
0

我正在使用反射來測試某個類是否具有特定的父類,然後返回它的一個實例。動態創建的對象上的依賴注入

if(class_exists($classname)){ 
      $cmd_class = new \ReflectionClass($classname); 
      if($cmd_class->isSubClassOf(self::$base_cmd)){ 
       // var_dump($cmd_class);exit; 
       return $cmd_class->newInstance(); 
      } 
     } 

我希望能夠單元測試這些實例化的對象,但我不知道是否有任何方式使用依賴注入在這種情況下。我的想法是使用工廠來獲得依賴關係。工廠模式是最佳選擇嗎?

回答

1

My thought was to use factories to get dependencies

通過使用這種方法,你仍然不知道哪些依賴一個類。 我會推薦更進一步,並使用Reflection API解決依賴關係。

實際上,您可以鍵入提示構造函數參數,並且Reflection API完全可以讀取類型提示。

這是一個非常簡單的例子:

<?php 

class Email { 

    public function send() 
    { 
     echo "Sending E-Mail"; 
    } 

} 

class ClassWithDependency { 

    protected $email; 

    public function __construct(Email $email) 
    { 
     $this->email = $email; 
    } 

    public function sendEmail() 
    { 
     $this->email->send(); 
    } 

} 


$class = new \ReflectionClass('ClassWithDependency'); 
// Let's get all the constructor parameters 
$reflectionParameters = $class->getConstructor()->getParameters(); 

$dependencies = []; 
foreach($reflectionParameters AS $param) 
{ 
    // We instantiate the dependent class 
    // and push it to the $dependencies array 
    $dependencies[] = $param->getClass()->newInstance(); 
} 

// The last step is to construct our base object 
// and pass in the dependencies array 
$instance = $class->newInstanceArgs($dependencies); 
$instance->sendEmail(); //Output: Sending E-Mail 

當然,你需要做的錯誤自己檢查(如果有例如用於構造函數的參數沒有Typehint)。此外這個例子不處理嵌套的依賴關係。但你應該得到基本的想法。

再想一想,你甚至可以組裝一個小的DI容器,在這裏你可以配置哪些實例注入某些類型提示。