2015-01-15 26 views
5

我試圖用ENVs在Symfony2中設置我的參數。標量值很容易,但我有參數是我需要用ENV設置的數組。用作Symfony參數的非標量ENV

有問題的參數:

parameters: 
    redis.servers: 
    - { host: 127.0.0.1, port: 6379 } 
    - { host: other, port: 6379 } 
    # and so on 

這裏踢球是服務器的陣列可以動態改變,所以我不能只是假設有2

我希望做的(但這只是給了我一串JSON):

SYMFONY__REDIS__SERVERS=[{"host":"127.0.0.1","port":"6379"}] 

這可能嗎?任何可行的解決方法?有多個bundle用於接受數組/對象參數,所以我不能在那裏進行更新來處理參數。如果有的話,它必須是應用程序級別。

謝謝。

回答

1

我能夠通過更新AppKernel來覆蓋父內核的getEnvParameters()方法來解決此問題。此方法僅在內核已在ENV中找到的參數(技術上來自$ _SERVER)上運行。我喜歡它,因爲它不會在整個參數堆棧上運行,也不會在整個$ _SERVER陣列上運行。

protected function getEnvParameters() 
{ 
    $parameters = parent::getEnvParameters(); 
    foreach ($parameters as &$parameter) { 
     if (is_string($parameter)) { 
      $decoded = json_decode($parameter, true); 
      // we only care about arrays (or objects that get turned into arrays) 
      if (!json_last_error() && is_array($decoded)) { 
       $parameter = $decoded; 
      } 
     } 
    } 

    return $parameters; 
}