Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony: Inject object (not service) to service constructor

Tags:

symfony

In the definition of my services, I'd like to pass as a service argument constructor an object not a service.

From config.yml:

services:
  acme.services.exampleservice:
    class:  Acme\ExampleBundle\Services\ExampleService
    arguments: 
        entityManager: "@doctrine.orm.entity_manager"
        httpClient: \Example\Http\Client\Client

Note the httpClient argument. This must be an instance of the \Example\Http\Client\Client class.

The above does not work - the string "\Example\Http\Client\Client" is passed as the httpClient argument to the service.

What is the syntax for achieving the above by means of passing an instance of \Example\Http\Client\Client to the service constructor?

like image 540
Jon Cram Avatar asked Jul 25 '12 16:07

Jon Cram


1 Answers

Create a private service. Here's what's written in the documentation:

If you use a private service as an argument to more than one other service, this will result in two different instances being used as the instantiation of the private service is done inline (e.g. new PrivateFooBar()).

services:
  acme.services.exampleservice:
    class:  Acme\ExampleBundle\Services\ExampleService
    arguments: 
        entityManager: "@doctrine.orm.entity_manager"
        httpClient: acme.services.httpClient

  acme.services.httpClient:
    class: Example\Http\Client\Client
    public: false

You will not be able to retrieve a private service from the container. From the outside it looks just as if you passed a regular object to the constructor of your service.

like image 149
kgilden Avatar answered Sep 28 '22 20:09

kgilden