John Davidson

php - Doctrine entity listener not firing using YAML configuration

0 comments
Message:


When i use the following annotation within an entity, the listener for it is called successfully. The problem with using the annotation rather than configuring it within the service config is that i cannot pass services into the listener through the constructor.


/**
@ORM\EntityListeners({CustomerLoadListener::class})
*/

I've tried setting the listener up in services.yaml using the following snippet:


services:
App\EventListener\CustomerLoadListener:
tags:
-
name: 'doctrine.orm.entity_listener'
event: 'postLoad'
entity: 'App\Entity\Customer'

Here is my event listener class:


<?php declare(strict_types = 1);

namespace App\EventListener;

use App\Entity\Customer;

class CustomerLoadListener
{
private CustomerService $customerService;

public function __construct(CustomerService $customerService)
{
$this->customerService = $customerService;
}

public function postLoad(Customer $customer): void
dd($customer);
// Do something with customer entity...
}
}

When i use the YAML config above, the listener is never called. yet the standard doctrine annotation works fine.


I want to use call the listener using the yaml variant so i can add custom arguments that are passed via its constructor.


The code works fine if i was to change the name of the event to 'doctrine.event_listener' instead of 'doctrine.orm.entity_listener'. The problem with that approach though is that the method would be called for every entity that is loaded which seems inefficient. I want it to only be called when a specific entity is loaded, which in my case is the Customer entity.


I just can't seem to figure out why when i use an entity_listener, it never seems to get called when i set it up in the yaml config.



My Answer:
One possible reason why your entity listener is not being called when configured in YAML could be due to the way you are defining the event in the YAML configuration.

Instead of using 'postLoad' as the event in the YAML configuration, try using 'doctrine.orm.entity_listener' as the event. This should match the event name used in the annotation and trigger the listener when the entity is loaded.

Here is an updated version of your services.yaml configuration:

yaml
services:
App\EventListener\CustomerLoadListener:
tags:
-
name: 'doctrine.orm.entity_listener'
event: 'doctrine.orm.entity_listener'
entity: 'App\Entity\Customer'


By using 'doctrine.orm.entity_listener' as the event in the YAML configuration, it should match the event name used in the annotation and trigger the listener when the Customer entity is loaded.

Make sure to clear the cache after making these changes to ensure that the updated configuration is loaded correctly.

Rate this post

5 of 5 based on 4732 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us