2016-08-08 59 views
0

我有一個容易的(我認爲)。對象陣列的內爆

我有一個Silex應用程序...我創建了一個服務services.yml文件,我的服務與他們的參數。 coruse的,參數可以是另一個類的實例:

services: 
    Service: 
     class: App\Services\xxxxxService 
     arguments: 
     - App\Lib\Parser\JsonParser 
     - xxxxxx 

所以,在我的init程序,我有這樣的一段代碼:

$services = $this['config']['services']; 

    foreach ($services as $name => $service) { 
     $className = $service['class']; 

     $args = array_map(function ($arg) { 
      if(class_exists($arg)){ 
       return new $arg; 
      } else { 
       return $arg; 
      } 
     }, $service['arguments']); 
     $args = implode(',', $args); 

     $this[$name] = new $className($this, $args); 
    } 

此代碼給我的錯誤:

可捕捉致命錯誤:類App \ Lib \ Parser \ JsonParser的對象無法轉換爲線252上的/app/src/Application.php中的字符串

我的目標是讓$ this [$ name] = new $類名($日是,$ args [0],$ args [1] ....),但我不能使用implode函數。

任何想法???

預先感謝您!

M.

回答

1

我建議使用ReflectionClass來實例$className

後您收集所有的$args不使用implode方法,因爲它無法通過正確的參數傳遞給類的構造函數。

所以,你必須$argsarray

array_unshift($args, $this); # Prepend $this in args 
$refl = new ReflectionClass($className); 
$this[$name] = $refl->newInstanceArgs($args); #Instatiate $className with appropriate args. 
+0

YESSS! ...反思能夠做到這一點! +1你! 您是否認爲Reflection在內存使用方面過於昂貴? 查看我的代碼,你認爲我是對的嗎? ....我有一個Silex \ Application的應用程序包裝器,在運行之前,我將所有控制器,參數和服務啓動到$ app中,這是Pimple的一個實例。 因此,在我的應用程序現在我有$ app ['myService'],我可以在任何地方重新使用。 – Mauro

+0

您正在嘗試構建一個DependencyInjection工具。雖然有很多,但建立你自己並不差,因爲你可以在這個過程中學到很多東西。爲了提高性能,如果您認爲速度較慢,最好對應用程序進行基準測試並進行性能分析。在分析中你可以看到瓶頸在哪裏。 ReflectionClass也是從Symfony DI中使用的,我認爲這是php中用於從args創建類實例的唯一wawy。 – Whiteulver