Passing a factory service to symfony 2

I have a class that depends on the connection to the database, something like this:

class Test { private $conn; public function __construct(Connection $conn) { $this->conn = $conn; } } 

A service for this might look like this:

  services: service.test: class: Test arguments: - ["@database_connection"] 

Now I want to transfer my own service / connection object, which creates Connection at startup. But I cannot pass this as an argument, because it wants a Connection object, not a factory.

How can I best approach this?

I tried adding setConnection to the Test class, but it would be better to keep the current definition and maintenance intact.

+5
source share
1 answer

Symfony Service Container has a truly turnkey solution.

Your database_connection service must be configured to use factory to create its instance. It will be something like this:

 services: database_connection: class: Connection factory: [ConnectionFactory, createConnection] 

And if the factory is also a service, it might look like this:

 services: database_connection: class: Connection factory: ["@connection_factory", createConnection] 

More information on this can be found here .

+6
source

All Articles