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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 matlab计算中误差
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊