Select an entity manager with Dependency Injection in Symfony

I have defined two different entity managers in doctrine.yaml

entity_managers:
            EM1:
                naming_strategy: doctrine.orm.naming_strategy.underscore
                mappings:
                    AppEM1:
                        is_bundle: false
                        type: annotation
                        dir: '%kernel.project_dir%/src/BC1/Domain/Entity'
                        prefix: 'BC1DomainEntity'
                        alias:  AppEM1
            EM2:
                naming_strategy: doctrine.orm.naming_strategy.underscore
                mappings:
                    AppEM2:
                        is_bundle: false
                        type: annotation
                        dir: '%kernel.project_dir%/src/BC2/Domain/Entity'
                        prefix: 'BC2DomainEntity'
                        alias:  AppEM2

and I am injecting a Doctrine EntityManagerInterface in my service:

service.yaml

    DoctrineRepository:
        class: BCInfrastructurePersistenceDoctrineRepository
        arguments:
            - "@DoctrineORMEntityManagerInterface"

DoctrineRepository.php

    public function __construct(
        EntityManagerInterface $client
    ) {
        $this->entityManager = $client;
    }

I want to be able to select which Entity Manager previously defined (EM1, EM2) I want to use when using DoctrineRepository. Idealy it would be something like:

$this->entityManager->useEntityManager('EM2');

Do I need to inject another service instead of a DoctrineORMEntityManagerInterface? I have debugged the entity managers load and I have found that it automatically assigns the first one when generating cache:

cache/dev/getDoctrineRepositoryService.php:

return $this->privates['DoctrineRepository'] = new BCInfrastructurePersistenceDoctrineRepository(($this->services['doctrine.orm.EM1_entity_manager'] ?? $this->load('getDoctrine_Orm_EM1EntityManagerService.php')));

Any help would be apreciated, thanks.

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *