title: How to programmatically set up Doctrine entity listener in Symfony?
body: <p>I have a Symfony 3.4 app and a Composer package with an <code>EntityChangeListener</code> to log entity property changes. The package also contains a <code>EntityListenerPass</code> (compiler pass) which iterates over a list of class names defined in app <code>config.yml</code> while building the service container. It programmatically tags the entity classes like this to notify the listener on <code>preUpdate</code> events:</p>
  
  <pre><code>$listener = $container-&gt;getDefinition('entity_history.listener.entity_change');
  $entities = $container-&gt;getExtensionConfig('entity_history')[0]['entities'];
  
  foreach ($entities as $className) {
      $listener-&gt;addTag('doctrine.orm.entity_listener', ['entity' =&gt; $className, 'event' =&gt; 'preUpdate']);
  }
  </code></pre>
  
  <p>Adding those tags causes a lot of errors which appear unrelated. In example undefined index errors inside the Doctrine UnitOfWork for the entity states. Also related entities which are loaded from database suddenly are recognised as <em>new</em> by Doctrine. Even object comparison inside a <code>switch</code> statement started to fail with:</p>
  
  <blockquote>
    <p>Fatal error: Nesting level too deep - recursive dependency?</p>
  </blockquote>
  
  <p>But without those listeners, everything works fine and all tests pass. Is there an alternative/better way to programmatically set up Doctrine entity listeners?</p>