Home > Mobile >  Doctrine Entity Listeners not working if APP_DEBUG=false
Doctrine Entity Listeners not working if APP_DEBUG=false

Time:01-09

I have a very strange behaviour concerning doctrine entity listeners. I have set up two doctrine entity listeners in a symfony 4.4 application.

The configuration in the service.yaml looks something like this:

services:
    App\EntityListener\MyEntityListener:
        tags:
            -   name: doctrine.orm.entity_listener
                event: preUpdate
                entity: App\Entity\MyEntity

I had the problem, that the entity listeners worked perfectly in local dev environment, but not in production. I have tracked the problem to the symfony debug mode. If the symfony kernel has debug=true, the entity listeners are called as expected. If it is set to false, the entity listeners are not attached to the entity classes metadata by doctrine for some reason. My first guess, was a problem in cache usage, but the problem persists if the cache is purged. Also I do not have any client code relying on Kernel::isDebug().

Does anyone have an idea where this problem might originate and can hint me in a direction where to look to solve this?

CodePudding user response:

After hours of searching and debugging I have found the root of the problem. I am using multiple entity managers in this project. While entity listeners are bound to one entity manager, the class metadata cache of doctrine is not. So when debug was set to true, there were no (real) cache hits and the class metadata was always built freshly. This garanteed, that the entity listeners were always present when needed. But when cache is used, the entity class metadata is built in the context of each entity manager responsible for the entity. But it is still written to the same cache storage. So if the first entity manager has a bunch of entity listeners on classes that are managed by another entity manager as well, the entity listeners will be removed in the cache entry, because the metadata entry will be overwritten.

To fix this problem one needs to be more specific about which entities are managed by what entity manager. It might also help to attach entity listeners specifically to the correct entity manager. Because if this is omitted, entity listeners are attached to the default entity manager only, but not to any other, and in this case behaviour as described here might occur.

  •  Tags:  
  • Related