Is there a way to modify the entity mapping config

2020-08-21 01:39发布

问题:

In my standard Symfony2-app I'm having a bunch of bundles with some entities. Some of these entities are not located in the standard folder the automapping of doctrine finds out (e.g. /src/Acme/DemoBundle/Entities) but in a different location.

I could easily use config.yml to tell doctrine to use a different location like this:

doctrine:
    orm:
        auto_mapping: false
        mappings:
           AcmeDemoBundle:
              type: annotation
              prefix: Acme\DemoBundle\Entities\
              dir: %kernel.cache_dir%\Acme\DemoBundle\Entities

This works. But say I'm having 10 bundles with a different mapping the config.yml gets bloated very fast. Is there another way, e.g. with a CompilerPass or via DependencyInjection, so I don't need to add all entities in my config.yml? I already looked into the DoctrineBundle, but had no luck so far.

回答1:

To answer myself:

the most simple way is to adjust the autoloading, there is no need to modify the settings. In Symfony's standard distribution in autoload.php you have to add another location to the registerNamespace-method:

$loader->registerNamespaces(array(
    [...]
    'Foo' => array(__DIR__.'/../src/dirA', __DIR__.'/../src/dirB')
));

Doctrine will then look for entities in the "Foo" namespace first in dirA and then in dirB if not found.



回答2:

You can include other configuration files using imports

# yaml
imports:
    - { resource: entities.yml }

<!-- xml -->
<imports>
    <import resource="enditites.xml" />
</imports>

// PHP
$loader->import('entities.php');

You don't even have to stick to a single file type. It's possible to import an xml configuration file to a yaml file, for example.