'Doctrine entity listener not firing using YAML configuration

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.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source