I'm using Doctrine 2 where I have multiple connections for DBAL. I have also multiple EntityManagers in ORM.
I need to be able to somehow autowire specific DBAL connection into other Symfony 3 services.
I can autowire any EntitiyManager using EntityManagerDecorator but don't know how to do the same with connection. I'm able to get the connection from EntityManager but I don't think it's the way to go.
Each DBAL connection is always accessible in service container with the following identifier:
where
[name]
is the connection namehttps://github.com/doctrine/DoctrineBundle/blob/master/Resources/doc/configuration.rst#doctrine-dbal-configuration
You can specify wrapper class for doctrine connections, no proxy class needed:
Connections should extend
Doctrine\DBAL\Connection
:and create service aliases:
I had the same issue and tested it more precisely what works and why.
WORK FOR MANY DBAL CONNECTIONS USING PROXY
EDIT: I have done some proxy abstract class. Now each my connection class inherited from this proxy. It works fine :)
My connection default class:
second connection:
Then I have added manually to my services file, for all my connections(2 connections) :
Then my connections are automatically autowiring when I use their types
INJECT CONNECTIONS FOR EACH SERVICE
The simplest option - but require create each service separately and inject connection name - it means manually wiring Arguments** in your services file(app/config/services.yml) e.g.
where connection_name is your connection name. In below example we have two connections in config.yml and this value could be “default” or “database2”:
WORK FOR ONLY ONE DBAL CONNECTION
Autowiring for DBAL Connections works fine when we have only one connection. If I leave only default connection(remove connection database 2 from config.yml) and add some path to be autowired in app/config/services.yml:
and if I use as type class Doctrine\DBAL\Connection in my Class, it means that I want inject default connection(@doctrine.dbal.default_connection) because I have the only one connection.
ANSWER
// Edited SimPod, the answer to your question is WORK FOR MANY DBAL CONNECTIONS USING PROXY or INJECT CONNECTIONS FOR EACH SERVICE as I described above.
I'm aware that you have managed with that issue but my answer can help the others.
A simpler solution can be:
Use in controller or services:
there is a new functionality in version 3.4 which gives the process much easier. See : Symfony 3.3 - Entity Manager injection into services with multiple database?