Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a factory to symfony 2 service

Tags:

php

symfony

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.

like image 272
Oli Avatar asked Jun 17 '16 09:06

Oli


1 Answers

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.

like image 60
Jakub Matczak Avatar answered Nov 04 '22 00:11

Jakub Matczak