doushifen4060
2016-06-17 09:39
浏览 5
已采纳

将工厂传递给symfony 2服务

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.

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongshi1869 2016-06-17 10:13
    已采纳

    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.

    打赏 评论

相关推荐 更多相似问题