How to store Doctrine entities outside of a Symfony bundle?

The DoctrineBundle and Doctrine bridge are the integration layer between the Doctrine ORM and Symfony. One of features they provide is an automatic registration of entity mappings.

As long as we follow conventions, like putting entities into the Entity folder or mappings into the Resources/config/doctrine folder, mappings will be configured for us. In the Symfony Standard Edition this behaviour is enabled by default, thanks to the auto mapping configuration option.

Entities

It's convenient, since we don't have to do much to start working with the ORM.

However, in some situations I found it better to put the entities in a more general namespace to separate them from the bundle. This way it's possible to share the entities between multiple bundles or projects in a clean way.

Best place to define the mapping configuration is the app/config/config.yml file:

doctrine:
    orm:
        # ...
        mappings:
            Acme:
                type: annotation
                is_bundle: false
                dir: %kernel.root_dir%/../src/Acme/Entity
                prefix: Acme\Entity
                alias: Acme

Our example uses the annotation driver and therefore the dir option is a path to our entities. If we used xml or yml drivers this would need to be changed to the path where mapping files are stored.

Prefix is a part of the namespace our entities belong to and should be unique between all the mappings.

With alias we can refer to the entities with a shorter syntax, so instead of:

$entityManager->getRepository('Acme\Entity\Invoice');

we'll be able to use:

$entityManager->getRepository('Acme:Invoice');

Finally, we can define as many mappings as we need, so it's still possible to group entities in separate namespaces:

doctrine:
    orm:
        # ...
        mappings:
            AcmeCustomer:
                type: annotation
                is_bundle: false
                dir: %kernel.root_dir%/../src/Acme/Customer/Entity
                prefix: Acme\Customer\Entity
                alias: Customer
            AcmeCms:
                type: yml
                is_bundle: false
                dir: %kernel.root_dir%/../src/Acme/Cms/Entity/config
                prefix: Acme\Cms\Entity
                alias: CMS
Jakub Zalas

Jakub Zalas

Agile PHP Developer, addicted to BDD and Symfony