Symfony 2: disable the Doctrine event listener in ContainerAwareCommand

I use several Doctrine listeners registered in the configuration file for some automatic updates (created_on, updated_on timestamps, etc.). Currently, I have implemented additional functions that require simplifying the search for ready-made values ​​in the database.

I am thinking of updating the Symfony command, which will prepare these values ​​instead of updating the SQL script (in fact, any change or update in the way the value is broken will require just this single command to be executed). However, this will also call the EventListeners mentioned above.

Is there a way to disable a specific EventLister for a single command?

+4
source share
2 answers

something like this should do the trick:

$searchedListener = null;
$em = $this->getDoctrine()->getManager();
foreach ($em->getEventManager()->getListeners() as $event => $listeners) {
    foreach ($listeners as $key => $listener) {
        if ($listener instanceof ListenerClassYouLookFor) {
            $searchedListener = $listener;
            break 2;
        }
    }
}
if ($searchedListener) {
    $evm = $em->getEventManager();
    $evm->removeEventListener(array('onFlush'), $searchedListener);
}
else { //listener not found

}
+6
source

It makes sense to wrap the logic inside the Doctrine listener around:

if ($this->enabled) {

Thus, everyone can understand that logic can be disabled or not.

You can use the parameter to enable or disable the code (see http://symfony.com/doc/current/service_container/parameters.html ).

my_doctrine_listener_enabled: true

In the command, you set the value to false:

$container->setParameter('my_doctrine_listener_enabled', false);

Since the parameter is changed at run time, I recommend that you not use it through the DIC, but through

$container->getParameter('my_doctrine_listener_enabled')

Or another approach could be:

  • Create an "enabled" variable inside a Doctrine listener
  • Doctrine
  • $this->myListener->enabled = false
0

All Articles