Symfony
sponsored by SensioLabs
Menu
  • About
  • Documentation
  • Screencasts
  • Cloud
  • Certification
  • Community
  • Businesses
  • News
  • Download
  1. Home
  2. Documentation
  3. Doctrine
  4. How to Work with multiple Entity Managers and Connections
  • Documentation
  • Book
  • Reference
  • Bundles
  • Cloud
Search by Algolia

How to Work with multiple Entity Managers and Connections

Edit this page

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

    <doctrine:config>
        <doctrine:dbal default-connection="default">
            <!-- configure these for your database server -->
            <doctrine:connection name="default"
                url="%env(resolve:DATABASE_URL)%"
                driver="pdo_mysql"
                server_version="5.7"
                charset="utf8mb4"
            />

            <!-- configure these for your database server -->
            <doctrine:connection name="customer"
                url="%env(resolve:DATABASE_CUSTOMER_URL)%"
                driver="pdo_mysql"
                server_version="5.7"
                charset="utf8mb4"
            />
        </doctrine:dbal>

        <doctrine:orm default-entity-manager="default">
            <doctrine:entity-manager name="default" connection="default">
                <doctrine:mapping
                    name="Main"
                    is_bundle="false"
                    type="annotation"
                    dir="%kernel.project_dir%/src/Entity/Main"
                    prefix="App\Entity\Main"
                    alias="Main"
                />
            </doctrine:entity-manager>

            <doctrine:entity-manager name="customer" connection="customer">
                <doctrine:mapping
                    name="Customer"
                    is_bundle="false"
                    type="annotation"
                    dir="%kernel.project_dir%/src/Entity/Customer"
                    prefix="App\Entity\Customer"
                    alias="Customer"
                />
            </doctrine:entity-manager>
        </doctrine:orm>
    </doctrine:config>
</container>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// config/packages/doctrine.php
use Symfony\Config\DoctrineConfig;

return static function (DoctrineConfig $doctrine) {
    $doctrine->dbal()->defaultConnection('default');

    // configure these for your database server
    $doctrine->dbal()
        ->connection('default')
        ->url(env('DATABASE_URL')->resolve())
        ->driver('pdo_mysql')
        ->serverVersion('5.7')
        ->charset('utf8mb4');

    // configure these for your database server
    $doctrine->dbal()
        ->connection('customer')
        ->url(env('DATABASE_CUSTOMER_URL')->resolve())
        ->driver('pdo_mysql')
        ->serverVersion('5.7')
        ->charset('utf8mb4');

    $doctrine->orm()->defaultEntityManager('default');
    $emDefault = $doctrine->orm()->entityManager('default');
    $emDefault->connection('default');
    $emDefault->mapping('Main')
        ->isBundle(false)
        ->type('annotation')
        ->dir('%kernel.project_dir%/src/Entity/Main')
        ->prefix('App\Entity\Main')
        ->alias('Main');

    $emCustomer = $doctrine->orm()->entityManager('customer');
    $emCustomer->connection('customer');
    $emCustomer->mapping('Customer')
        ->isBundle(false)
        ->type('annotation')
        ->dir('%kernel.project_dir%/src/Entity/Customer')
        ->prefix('App\Entity\Customer')
        ->alias('Customer')
    ;
};

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 the prod environment configuration and in the Doctrine migrations configuration (if you use that):

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

# ...
1
2
3
4
# config/packages/doctrine_migrations.yaml
doctrine_migrations:
    # ...
    em: 'your default entity manager name'

When working with multiple connections to create your databases:

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

# Play only with "customer" connection
$ php bin/console doctrine:database:create --connection=customer

When working with multiple entity managers to generate migrations:

1
2
3
4
5
6
7
# Play only with "default" mappings
$ php bin/console doctrine:migrations:diff
$ php bin/console doctrine:migrations:migrate

# Play only with "customer" mappings
$ php bin/console doctrine:migrations:diff --em=customer
$ 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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// src/Controller/UserController.php
namespace App\Controller;

// ...
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\Persistence\ManagerRegistry;

class UserController extends AbstractController
{
    public function index(ManagerRegistry $doctrine): Response
    {
        // Both methods return the default entity manager
        $entityManager = $doctrine->getManager();
        $entityManager = $doctrine->getManager('default');

        // This method returns instead the "customer" entity manager
        $customerEntityManager = $doctrine->getManager('customer');

        // ...
    }
}

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// src/Controller/UserController.php
namespace App\Controller;

use AcmeStoreBundle\Entity\Customer;
use AcmeStoreBundle\Entity\Product;
use Doctrine\Persistence\ManagerRegistry;
// ...

class UserController extends AbstractController
{
    public function index(ManagerRegistry $doctrine): Response
    {
        // Retrieves a repository managed by the "default" entity manager
        $products = $doctrine->getRepository(Product::class)->findAll();

        // Explicit way to deal with the "default" entity manager
        $products = $doctrine->getRepository(Product::class, 'default')->findAll();

        // Retrieves a repository managed by the "customer" entity manager
        $customers = $doctrine->getRepository(Customer::class, 'customer')->findAll();

        // ...
    }
}

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
2
3
4
5
6
7
8
9
// src/Repository/CustomerRepository.php
namespace App\Repository;

use Doctrine\ORM\EntityRepository;

class CustomerRepository extends EntityRepository
{
    // ...
}

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.
We stand with Ukraine.
Version:

Symfony 6.2 is backed by

Symfony 6.2 is backed by

Measure & Improve Symfony Code Performance

Measure & Improve Symfony Code Performance

Peruse our complete Symfony & PHP solutions catalog for your web development needs.

Peruse our complete Symfony & PHP solutions catalog for your web development needs.

↓ Our footer now uses the colors of the Ukrainian flag because Symfony stands with the people of Ukraine.

Avatar of mousezheng, a Symfony contributor

Thanks mousezheng for being a Symfony contributor

2 commits • 92 lines changed

View all contributors that help us make Symfony

Become a Symfony contributor

Be an active part of the community and contribute ideas, code and bug fixes. Both experts and newcomers are welcome.

Learn how to contribute

Symfony™ is a trademark of Symfony SAS. All rights reserved.

  • What is Symfony?
    • Symfony at a Glance
    • Symfony Components
    • Case Studies
    • Symfony Releases
    • Security Policy
    • Logo & Screenshots
    • Trademark & Licenses
    • symfony1 Legacy
  • Learn Symfony
    • Symfony Docs
    • Symfony Book
    • Reference
    • Bundles
    • Best Practices
    • Training
    • eLearning Platform
    • Certification
  • Screencasts
    • Learn Symfony
    • Learn PHP
    • Learn JavaScript
    • Learn Drupal
    • Learn RESTful APIs
  • Community
    • SymfonyConnect
    • Support
    • How to be Involved
    • Code of Conduct
    • Events & Meetups
    • Projects using Symfony
    • Downloads Stats
    • Contributors
    • Backers
  • Blog
    • Events & Meetups
    • A week of symfony
    • Case studies
    • Cloud
    • Community
    • Conferences
    • Diversity
    • Documentation
    • Living on the edge
    • Releases
    • Security Advisories
    • SymfonyInsight
    • Twig
    • SensioLabs
  • Services
    • SensioLabs services
    • Train developers
    • Manage your project quality
    • Improve your project performance
    • Host Symfony projects
    Deployed on
Follow Symfony
Search by Algolia