Search code examples
symfonyautowiredentitymanager

How to use Symfony autowiring with multiple entity managers


I would like to use the autowiring in a service that use 2 different entity manager. How to achieve something like that ?

use Doctrine\ORM\EntityManager;
class TestService
{
    public function __construct(EntityManager $emA, EntityManager $emB)
    {
    }
}

My service.yml file use to be configured like that :

    app.testservice:
        class: App\Services\TestService
        arguments:
            - "@doctrine.orm.default_entity_manager"
            - "@doctrine.orm.secondary_entity_manager"

Solution

  • Dylan's answer violates the Demeter's Law principle. It's very easy and elegant since Symfony 3.4, meet Local service binding:

    services:
      _defaults:
        bind:
          $emA: "@doctrine.orm.default_entity_manager"
          $emB: "@doctrine.orm.secondary_entity_manager"
    

    Then in your service the autoloading will do the hard work for you:

    class TestService
    {
        public function __construct(EntityManager $emA, EntityManager $emB)
        {
            …
        }
    }