How to Work with multiple Entity Managers and Connections

How to Work with multiple Entity Managers and Connections

You can use multiple Doctrine entity managers or connections in a Symfony application. This is necessary if you are using different databases or even vendors with entirely different sets of entities. In other words, one entity manager that connects to one database will handle some entities while another entity manager that connects to another database might handle the rest. It is also possible to use multiple entity managers to manage a common set of entities, each with their own database connection strings or separate cache configuration.

Note

Using multiple entity managers is not complicated to configure, but more advanced and not usually required. Be sure you actually need multiple entity managers before adding in this layer of complexity.

Caution

Entities cannot define associations across different entity managers. If you need that, there are several alternatives that require some custom setup.

The following configuration code shows how you can configure two entity managers:

  • YAML

    1. # config/packages/doctrine.yaml
    2. doctrine:
    3. dbal:
    4. default_connection: default
    5. connections:
    6. default:
    7. # configure these for your database server
    8. url: '%env(resolve:DATABASE_URL)%'
    9. driver: 'pdo_mysql'
    10. server_version: '5.7'
    11. charset: utf8mb4
    12. customer:
    13. # configure these for your database server
    14. url: '%env(resolve:DATABASE_CUSTOMER_URL)%'
    15. driver: 'pdo_mysql'
    16. server_version: '5.7'
    17. charset: utf8mb4
    18. orm:
    19. default_entity_manager: default
    20. entity_managers:
    21. default:
    22. connection: default
    23. mappings:
    24. Main:
    25. is_bundle: false
    26. type: annotation
    27. dir: '%kernel.project_dir%/src/Entity/Main'
    28. prefix: 'App\Entity\Main'
    29. alias: Main
    30. customer:
    31. connection: customer
    32. mappings:
    33. Customer:
    34. is_bundle: false
    35. type: annotation
    36. dir: '%kernel.project_dir%/src/Entity/Customer'
    37. prefix: 'App\Entity\Customer'
    38. alias: Customer
  • XML

    1. <!-- config/packages/doctrine.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <container xmlns="http://symfony.com/schema/dic/services"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xmlns:doctrine="http://symfony.com/schema/dic/doctrine"
    6. xsi:schemaLocation="http://symfony.com/schema/dic/services
    7. https://symfony.com/schema/dic/services/services-1.0.xsd
    8. http://symfony.com/schema/dic/doctrine
    9. https://symfony.com/schema/dic/doctrine/doctrine-1.0.xsd">
    10. <doctrine:config>
    11. <doctrine:dbal default-connection="default">
    12. <!-- configure these for your database server -->
    13. <doctrine:connection name="default"
    14. url="%env(resolve:DATABASE_URL)%"
    15. driver="pdo_mysql"
    16. server_version="5.7"
    17. charset="utf8mb4"
    18. />
    19. <!-- configure these for your database server -->
    20. <doctrine:connection name="customer"
    21. url="%env(resolve:DATABASE_CUSTOMER_URL)%"
    22. driver="pdo_mysql"
    23. server_version="5.7"
    24. charset="utf8mb4"
    25. />
    26. </doctrine:dbal>
    27. <doctrine:orm default-entity-manager="default">
    28. <doctrine:entity-manager name="default" connection="default">
    29. <doctrine:mapping
    30. name="Main"
    31. is_bundle="false"
    32. type="annotation"
    33. dir="%kernel.project_dir%/src/Entity/Main"
    34. prefix="App\Entity\Main"
    35. alias="Main"
    36. />
    37. </doctrine:entity-manager>
    38. <doctrine:entity-manager name="customer" connection="customer">
    39. <doctrine:mapping
    40. name="Customer"
    41. is_bundle="false"
    42. type="annotation"
    43. dir="%kernel.project_dir%/src/Entity/Customer"
    44. prefix="App\Entity\Customer"
    45. alias="Customer"
    46. />
    47. </doctrine:entity-manager>
    48. </doctrine:orm>
    49. </doctrine:config>
    50. </container>
  • PHP

    1. // config/packages/doctrine.php
    2. $container->loadFromExtension('doctrine', [
    3. 'dbal' => [
    4. 'default_connection' => 'default',
    5. 'connections' => [
    6. // configure these for your database server
    7. 'default' => [
    8. 'url' => '%env(resolve:DATABASE_URL)%',
    9. 'driver' => 'pdo_mysql',
    10. 'server_version' => '5.7',
    11. 'charset' => 'utf8mb4',
    12. ],
    13. // configure these for your database server
    14. 'customer' => [
    15. 'url' => '%env(resolve:DATABASE_CUSTOMER_URL)%',
    16. 'driver' => 'pdo_mysql',
    17. 'server_version' => '5.7',
    18. 'charset' => 'utf8mb4',
    19. ],
    20. ],
    21. ],
    22. 'orm' => [
    23. 'default_entity_manager' => 'default',
    24. 'entity_managers' => [
    25. 'default' => [
    26. 'connection' => 'default',
    27. 'mappings' => [
    28. 'Main' => [
    29. 'is_bundle' => false,
    30. 'type' => 'annotation',
    31. 'dir' => '%kernel.project_dir%/src/Entity/Main',
    32. 'prefix' => 'App\Entity\Main',
    33. 'alias' => 'Main',
    34. ]
    35. ],
    36. ],
    37. 'customer' => [
    38. 'connection' => 'customer',
    39. 'mappings' => [
    40. 'Customer' => [
    41. 'is_bundle' => false,
    42. 'type' => 'annotation',
    43. 'dir' => '%kernel.project_dir%/src/Entity/Customer',
    44. 'prefix' => 'App\Entity\Customer',
    45. 'alias' => 'Customer',
    46. ]
    47. ],
    48. ],
    49. ],
    50. ],
    51. ]);

In this case, you’ve defined two entity managers and called them default and customer. The default entity manager manages entities in the src/Entity/Main directory, while the customer entity manager manages entities in src/Entity/Customer. You’ve also defined two connections, one for each entity manager, but you are free to define the same connection for both.

Caution

When working with multiple connections and entity managers, you should be explicit about which configuration you want. If you do omit the name of the connection or entity manager, the default (i.e. default) is used.

If you use a different name than default for the default entity manager, you will need to redefine the default entity manager in prod environment configuration too:

  1. # config/packages/prod/doctrine.yaml
  2. doctrine:
  3. orm:
  4. default_entity_manager: 'your default entity manager name'
  5. # ...

When working with multiple connections to create your databases:

  1. # Play only with "default" connection
  2. $ php bin/console doctrine:database:create
  3. # Play only with "customer" connection
  4. $ php bin/console doctrine:database:create --connection=customer

When working with multiple entity managers to generate migrations:

  1. # Play only with "default" mappings
  2. $ php bin/console doctrine:migrations:diff
  3. $ php bin/console doctrine:migrations:migrate
  4. # Play only with "customer" mappings
  5. $ php bin/console doctrine:migrations:diff --em=customer
  6. $ php bin/console doctrine:migrations:migrate --em=customer

If you do omit the entity manager’s name when asking for it, the default entity manager (i.e. default) is returned:

  1. // src/Controller/UserController.php
  2. namespace App\Controller;
  3. // ...
  4. use Doctrine\ORM\EntityManagerInterface;
  5. class UserController extends AbstractController
  6. {
  7. public function index(EntityManagerInterface $entityManager): Response
  8. {
  9. // These methods also return the default entity manager, but it's preferred
  10. // to get it by injecting EntityManagerInterface in the action method
  11. $entityManager = $this->getDoctrine()->getManager();
  12. $entityManager = $this->getDoctrine()->getManager('default');
  13. $entityManager = $this->get('doctrine.orm.default_entity_manager');
  14. // Both of these return the "customer" entity manager
  15. $customerEntityManager = $this->getDoctrine()->getManager('customer');
  16. $customerEntityManager = $this->get('doctrine.orm.customer_entity_manager');
  17. // ...
  18. }
  19. }

Entity managers also benefit from autowiring aliases when the framework bundle is used. For example, to inject the customer entity manager, type-hint your method with EntityManagerInterface $customerEntityManager.

You can now use Doctrine like you did before - using the default entity manager to persist and fetch entities that it manages and the customer entity manager to persist and fetch its entities.

The same applies to repository calls:

  1. // src/Controller/UserController.php
  2. namespace App\Controller;
  3. use AcmeStoreBundle\Entity\Customer;
  4. use AcmeStoreBundle\Entity\Product;
  5. // ...
  6. class UserController extends AbstractController
  7. {
  8. public function index(): Response
  9. {
  10. // Retrieves a repository managed by the "default" em
  11. $products = $this->getDoctrine()
  12. ->getRepository(Product::class)
  13. ->findAll()
  14. ;
  15. // Explicit way to deal with the "default" em
  16. $products = $this->getDoctrine()
  17. ->getRepository(Product::class, 'default')
  18. ->findAll()
  19. ;
  20. // Retrieves a repository managed by the "customer" em
  21. $customers = $this->getDoctrine()
  22. ->getRepository(Customer::class, 'customer')
  23. ->findAll()
  24. ;
  25. // ...
  26. }
  27. }

Caution

One entity can be managed by more than one entity manager. This however results in unexpected behavior when extending from ServiceEntityRepository in your custom repository. The ServiceEntityRepository always uses the configured entity manager for that entity.

In order to fix this situation, extend EntityRepository instead and no longer rely on autowiring:

  1. // src/Repository/CustomerRepository.php
  2. namespace App\Repository;
  3. use Doctrine\ORM\EntityRepository;
  4. class CustomerRepository extends EntityRepository
  5. {
  6. // ...
  7. }

You should now always fetch this repository using ManagerRegistry::getRepository().

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.