使用Symfony2创建服务

ElP*_*ter 1 php service symfony

使用symfony2我遵循此文档来创建和使用服务来执行常规任务.

我几乎已经完成了,但我还有一个问题(当然是由于对Symfony2中服务容器的一些误解.

这个类是这样的:

class MyClass{
    private $myProperty;

    public funciton performSomethingGeneral{
        return $theResult;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,在我的config.yml中:

services:
    myService:
        class: Acme\MyBundle\Service\MyClass
        arguments: [valueForMyProperty]
Run Code Online (Sandbox Code Playgroud)

最后,在我的控制器中:

$myService = $this -> container -> get('myService');
Run Code Online (Sandbox Code Playgroud)

在那一行之后,当我检查时$myService,我仍然看到$ myService - > $ myProperty为未初始化.

有些事情我没有得到妥善处理.我还需要做些什么来初始化属性并准备好使用之前配置的值config.yml?我如何设置多个属性?

dev*_*ler 6

arguments 从你的yml文件传递给你的服务的构造函数,所以你应该在那里处理它.

services:
    myService:
        class: Acme\MyBundle\Service\MyClass
        arguments: [valueForMyProperty, otherValue]
Run Code Online (Sandbox Code Playgroud)

和PHP:

class MyClass{
    private $myProperty;
    private $otherProperty;

    public funciton __construct($property1, $property2){
         $this->myProperty = $property1;   
         $this->otherProperty = $property2;   
    }
}
Run Code Online (Sandbox Code Playgroud)