Search code examples
symfonydoctrineentity-relationshipsymfony-2.2

Symfony 2.2 Doctrine ResolveTargetEntities Listener


I'm creating a bundle with relationship associations. In order to keep things abstract, I'd like to use Doctrine's brand new ResolveTargetEntities listener.

The thing is that I would like the setup of the listener to be automated, so future developers using my bundle won't need to configure the listener themselves.

In my bundle, there's a config parameter called data_class, which I would like to use to setup the ResolveTargetEntities listener:

# app/config/config.yml
my_bundle:
    City:
        data_class: Acme\DemoBundle\Entity\City

How can I setup a service, or a config file within my bundle to configure the listener using this parameter? Something like this:

resolve_target_entities:
    Dev\MyBundle\Model\City: %my_bundle.City.data_class%

EDIT:

The above configuration example is provided to show what should be accomplished by doctrine, but the object of this question is to find a way to setup the ResolveTargetEntities listener automatically, using a service, a dependency injection container, or any other way that requires the end user to provide only one parameter under the my_bundle namespace: data_class


Solution

  • See https://github.com/doctrine/doctrine2/blob/master/docs/en/cookbook/resolve-target-entity-listener.rst

    Next, we need to configure the listener. Add this to the area you set up Doctrine. You must set this up in the way outlined below, otherwise you can not be guaranteed that the targetEntity resolution will occur reliably: $evm = new \Doctrine\Common\EventManager;

    $rtel = new \Doctrine\ORM\Tools\ResolveTargetEntityListener;
    $rtel->addResolveTargetEntity('Acme\\InvoiceModule\\Model\\InvoiceSubjectInterface',
        'Acme\\CustomerModule\\Entity\\Customer', array());
    
    // Add the ResolveTargetEntityListener
    $evm->addEventSubscriber($rtel);
    
    $em = \Doctrine\ORM\EntityManager::create($connectionOptions, $config, $evm);