使用多个连接时自动装配特定的 DBAL 连接

sim*_*Pod 3 doctrine symfony dbal

我正在使用 Doctrine 2,其中我有多个 DBAL 连接。我在 ORM 中也有多个 EntityManager。

我需要能够以某种方式将特定的 DBAL 连接自动连接到其他 Symfony 3 服务中。

我可以使用 EntityManagerDecorator 自动装配任何 EntitiyManager 但不知道如何对连接执行相同的操作。我能够从 EntityManager 获得连接,但我认为这不是可行的方法。

Guz*_*zik 8

您可以为学说连接指定包装类,不需要代理类:

#config.yml
doctrine:
    dbal:
        connections:
            default:
                wrapper_class: AppBundle\Connections\ConnectionDefault
                ...
            second:
                wrapper_class: AppBundle\Connections\ConnectionSecond
                ...
Run Code Online (Sandbox Code Playgroud)

连接应该扩展Doctrine\DBAL\Connection

<?php

namespace AppBundle\Connection;

use Doctrine\DBAL\Connection;

class ConnectionDefault extends Connection
{

}

class ConnectionSecond extends Connection
{

}
Run Code Online (Sandbox Code Playgroud)

并创建服务别名:

#services.yml
services:
    ...
    AppBundle\Connections\ConnectionDefault: '@doctrine.dbal.default_connection'
    AppBundle\Connections\ConnectionSecond: '@doctrine.dbal.second_connection'
Run Code Online (Sandbox Code Playgroud)

然后您可以通过键入提示简单地将所需的连接注入服务:

class MyService {
    public function __construct(ConnectionDefault $connection) {...}
}

class MyOtherService {
    public function __construct(ConnectionSecond $connection) {...}
}
Run Code Online (Sandbox Code Playgroud)