Automatic mapping to default entity manager in symfony

Using the doctrine package, I am creating a package that requires a different database connection than the default one.

The package creates a new entity_manager that uses the new connection via configuration:

doctrine:
  orm:
    entity_managers:
       default:....
       my_custom_em:
          connection: my_custom_connection
          mappings:
            MyBundle: ~

      

When trying to access the repository using $this->getContainer()->get('doctrine')->getRepository('MyBundle:AnEntity');

, I have an error:

  Unknown Entity namespace alias 'MyBundle'.

      

But when using the custom entity manager name, it works: $this->getContainer()->get('doctrine')->getRepository('MyBundle:AnEntity', 'my_custom_em');

Is there no way for doctrine to find out what MyBundle

should be mapped to this entity manager?

+3


source to share


1 answer


Unfortunately, this auto_mapping

can only be used when setting up one connection, so there is no simple one-line configuration that solves the problem.

There is a simple solution anyway.

Use RegistryManager

Anyway, when you call $this->getContainer()->get('doctrine')

, you get an instance ManagerRegistry

( see docs ) that has a method getManagerForClass

. With this method, you can write code that is independent of the connection configuration.

Your example would become:

$class = 'MyBundle:AnEntity';
$manager = $this->getContainer()->get('doctrine')->getManagerForClass($class);
$manager->getRepository($className)

      

Define ObjectManager as a Service



If special handling is only required for one package, you can make an even better solution from the previous approach.

You can define a service that will transparently display RegistryManager

for you.

In service.xml

you can write:

<parameters>
    <parameter key="my.entity.an_entity.class">Acme\MyBundle\Entity\AnEntity</parameter>
</parameters>

<services>
    <service id="my.manager"
             class="Doctrine\Common\Persistence\ObjectManager"
             factory-service="doctrine" factory-method="getManagerForClass">
         <argument>%my.entity.an_entity.class%</argument>
    </service>

    <service id="my.an_entity_repository"
             class="Doctrine\Common\Persistence\ObjectRepository"
             factory-service="my.manager" factory-method="getRepository">
         <argument>%my.entity.an_entity.class%</argument>
    </service>
</services>

      

Your example would become:

$class = 'MyBundle:AnEntity';

$repository = $this->getContainer()->get('my.manager')->getRepository($class);
// or
$repository = $this->getContainer()->get('my.an_entity_repository')

      

0


source







All Articles