2012-10-27 92 views
1

使用symfony2我正在關注this documentation以創建和使用服務來執行常規任務。 。使用Symfony2創建服務

我有差不多了,但我有一個問題,但(當然由於Symfony2中的服務容器一些誤解

類是這樣的:

class MyClass{ 
    private $myProperty; 

    public funciton performSomethingGeneral{ 
     return $theResult; 
    } 
} 

現在,在我的config.yml:

services: 
    myService: 
     class: Acme\MyBundle\Service\MyClass 
     arguments: [valueForMyProperty] 

最後,在我的控制器:

$myService = $this -> container -> get('myService'); 

之後,當我檢查$myService,我仍然看到$ myService - > $ myProperty爲未初始化。

有一些我沒有得到正確的。我還需要做些什麼才能使屬性初始化並準備好在config.yml中使用先前配置的值?我將如何設置多個屬性?

回答

5

arguments從你的yml文件傳遞給你的服務的構造函數,所以你應該在那裏處理它。

services: 
    myService: 
     class: Acme\MyBundle\Service\MyClass 
     arguments: [valueForMyProperty, otherValue] 

和php:

class MyClass{ 
    private $myProperty; 
    private $otherProperty; 

    public funciton __construct($property1, $property2){ 
     $this->myProperty = $property1; 
     $this->otherProperty = $property2; 
    } 
} 
+0

這就是它! :D謝謝:) – ElPiter