Create Service with Symfony2

2019-08-07 11:30发布

Using symfony2 I am following this documentation to create and use a service for performing a general task.

I have it almost done, but I have one problem yet (surely due to some misunderstanding on service containers in Symfony2.

The class is something like this:

class MyClass{
    private $myProperty;

    public funciton performSomethingGeneral{
        return $theResult;
    }
}

Now, in my config.yml:

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

Finally, in my controller:

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

After that line, When I inspect $myService, I still see $myService -> $myProperty as uninitialized.

There is something I am not getting properly. What else do I have to do to get the property initialized and ready to use with a previously configured value in config.yml? And how would I set more than one property?

1条回答
淡お忘
2楼-- · 2019-08-07 12:21

arguments from your yml file are passed to the constructor of your service, so you should handle it there.

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

and php:

class MyClass{
    private $myProperty;
    private $otherProperty;

    public funciton __construct($property1, $property2){
         $this->myProperty = $property1;   
         $this->otherProperty = $property2;   
    }
}
查看更多
登录 后发表回答