Jon Cram
Jon Cram

Reputation: 17309

Symfony: Inject object (not service) to service constructor

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?

Upvotes: 10

Views: 5305

Answers (1)

kgilden
kgilden

Reputation: 10356

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.

Upvotes: 19

Related Questions