I use doctrine entity listeners to send mail whenever an entity is created. I want to be able to disable this event listener when performing certain operations (fixtures are mailbombing me as soon as I try to populate my database with fake entities).
I tried to disable the listener by using the clear method of the EntityListenerResolver class without success.
Here is my listener configuration:
services:
mail_on_create_document_listener:
class: App\EventListener\MailOnCreateDocumentListener
autowire: true
tags:
-
name: 'doctrine.orm.entity_listener'
event: 'postPersist'
entity: 'App\Entity\Document'
I try to disable the listener with this code:
<?php
namespace App\DataFixtures;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Common\Persistence\ObjectManager;
class DebugFixture extends Fixture implements FixtureGroupInterface
{
public function load(ObjectManager $manager)
{
$manager->getConfiguration()->getEntityListenerResolver()->clear(MailOnCreateDocumentListener::class);
dump($manager->getConfiguration()->getEntityListenerResolver());
}
}
Here is the resulting dump of the EntityListenerResolver
^ Doctrine\Bundle\DoctrineBundle\Mapping\ContainerEntityListenerResolver^ {#1233
-container: Symfony\Component\DependencyInjection\Argument\ServiceLocator^ {#5278
-factory: Symfony\Component\DependencyInjection\Container::getService($registry, string $id, ?string $method, $load)^ {#283
this: ContainerHYiq7Ex\srcApp_KernelDevDebugContainer {#4404 …}
}
-serviceMap: array:1 [
"mail_on_create_document_listener" => array:4 [
0 => "privates"
1 => "mail_on_create_document_listener"
2 => "getMailOnCreateDocumentListenerService.php"
3 => true
]
]
-serviceTypes: array:1 [
"mail_on_create_document_listener" => "?"
]
-externalId: null
-container: null
-factories: array:1 [
"mail_on_create_document_listener" => array:4 [
0 => "privates"
1 => "mail_on_create_document_listener"
2 => "getMailOnCreateDocumentListenerService.php"
3 => true
]
]
-loading: []
-providedTypes: null
}
-instances: []
-serviceIds: array:1 [
"App\EventListener\MailOnCreateDocumentListener" => "mail_on_create_document_listener"
]
}
Reading the code, it seems that the clear from EntityListenerResolver affects the instance part, but not the serviceIds.
How does this clear method is supposed to work? Is my service declaration wrong?
EDIT: I also tried this code with no success
$evm = $manager->getEventManager();
$listeners = $evm->getListeners("postPersist");
while (count($listeners))
{
$evm->removeEventListener(array("postPersist"), array_pop($listeners));
}
But I read that entity listeners were quite different from other listeners, though it was not clear which was the difference. Here is the quote from the doc:
Different from Events an Entity Listener is invoked just to the specified entity