2017-02-28 15 views
2

我想從parameters.yml中讀取一個pareameter。 解決辦法是延長控制器,但我得到這個錯誤:Symfony:從控制器外部的parameter.yml中讀取

Error: Call to a member function getParameter() on null 

我知道容器是空的,但我不知道怎麼弄的容器?

class Configuration extends Controller 
{ 
    public function __construct() 
    { 
    $this->tempFolderPath = sys_get_temp_dir(); 
    $parameter = $this->container->getParameter('a'); 
    } 
} 

任何解決方案?任何幫助?

+0

http://symfony.com/doc/current/service_container.html閱讀本文檔,你會發現你的ANS – Shefali

回答

5

由於Container被注入到這樣的類中,所以在Controller中調用$this->container->getParameter('a')的類是可能的。當你在其他課程中,你需要注入你想要的參數defining your class as a service

您的服務定義將看起來像:

services: 
    class: App\Your\FooClass 
    arguments: 
     - %a% 

% - 這是特殊字符注入參數

那麼你的類將是這樣的:

class FooClass 
{ 
    protected $a; 

    public function __construct($a) 
    { 
     $this->a = $a; 
     //you have your "a" parameter value injected into constructor 
    } 
} 
+0

感謝快速幫助,但我在這個類實例化這個類的靜態mmethod:如果(self :: $ defaultConfiguration === null){ self :: $ defaultConfiguration = new Configuration(); } return self :: $ defaultConfiguration; } –

+1

這就是爲什麼靜態方法不好:)我會建議使用靜態方法退出。如果沒有,你將不得不手動解析你的'parameters.yml'並嘗試提取參數值,但這個非常優雅的解決方案 –

+0

不幸的是,我應該這樣做,感謝您的幫助! –

0

這是不是最佳做法,但對我來說這個是唯一的解決方案 :(因爲在我的代碼中我有一個靜態方法來實例化孔類。 所以解決方案將是。

public function __construct() 
{ 
    $this->tempFolderPath = sys_get_temp_dir(); 
    global $kernel; 
    $this->host = $kernel->getContainer()->getParameter('ws_host'); 
}