Oli
Oli

Reputation: 2452

Passing a factory to symfony 2 service

I have a class which is dependent on a DB connection, something like this:

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

The service for this could look like this:

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

Now, I'd like to pass my own connection service / object that at startup creates a Connection. But I can't pass it as an argument as it wants a Connection object, not a factory.

How can I best approach this?

I've tried adding a setConnection on the Test class, but it would be nicer to keep the current definition and service intact.

Upvotes: 5

Views: 235

Answers (1)

Jakub Matczak
Jakub Matczak

Reputation: 15656

There is actually ready solution for that in Symfony's Service Container.

Your database_connection service should be configured to use a factory to create its instance. That would be something like this:

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

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

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

More information about that can be found here.

Upvotes: 6

Related Questions