Working on several projects which use the same database, we made a Symfony2 Bundle to map all common functions.
Now the issue is that we have a second database, and we need the same kind of service, just as the first one.
config.yml
doctrine:
dbal:
default_connection: main
connections:
main:
/* ... */
sub:
/* ... */
orm:
default_entity_manager: main
entity_managers:
main:
connection: main
mappings:
AcmeMainBundle: ~
sub:
connection: sub
mappings:
AcmeSubBundle: ~
auto_generate_proxy_classes: %kernel.debug%
@AcmeMainBundle > services.yml
services:
mainmanager:
class: Acme\MainBundle\MainManager
arguments: [ @doctrine.orm.entity_manager ]
Acme\MainBundle\MainManager
class MainManager
{
public function __construct(EntityManager $em)
{
$em->getRepository('AcmeMainBundle:Foo');
}
}
This set works fine, I get all expected results since default_entity_manager
is set to main
which is the right EntityManager.
But now here's the issue.
@AcmeSubBundle > services.yml
submanager:
class: Acme\SubBundle\SubManager
arguments: [ @doctrine.orm.entity_manager ]
Acme\SubBundle\SubManager
class SubManager
{
public function __construct(EntityManager $em)
{
$em->getRepository('AcmeSubBundle:Bar'); // Throws exception
}
}
Unknown entity namespace alias AcmeSubBundle
Since EntityManager
goes into main
by default.
My question is, is there a "clean" way to inject a specific entity manager as argument in services.yml ?
Here is a way to pass a specific entity manager from
services.yml
Doctrine generates a new service name relative to their names.
Example:
In this case, it generates 2 others entity manager
The argument passed is a
Doctrine\ORM\EntityManager
objectIn my case:
services.yml
An alternative to this would be to directly give the repository instead of the manager.
To do such, you must create a service which will hold the repository.
services.yml
We let doctrine generate the given repository.
Then we can inject it in another service