Doctrine Events using the soft delete

Many projects use the soft delete strategy to avoid potential data loss.
Compared to Doctrine Event, a soft delete could be an update or remove event? maybe another thing? Let’s dig about it.

Typically, Doctrine is an ORM which Dispatches some event when interacting with the database. discover all the life cycle events in doctrine

Use case

On every delete of the entity Foo, do some specific logic

Reminder

Using a soft delete make an update for the row by updating a column that differs deleted and undeleted rows.

To solve the issue, Symfony give you the possibility to create a subscriber or listener which can listen to the doctrine events.

use Doctrine\Common\EventSubscriber;

class FooSubscriber implements EventSubscriber
{

/**
     * @return array
     */
    public function getSubscribedEvents()
    {
        return [
            'postRemove'
        ];
    }

    /**
     * @param LifecycleEventArgs $args
     */
    public function postRemove(LifecycleEventArgs $args)
    {
        $entity = $args->getEntity():
        // do something
    }
}

Don’t forget to declare your subscriber in your services.yml

Unfortunately, the subscriber can’t listen to the post remove Event, because doctrine is waiting for a delete query to fire it (post remove) while the soft delete makes an update instead.

The solution is there is another event called postSoftDelete which can make us able do to some logic in those cases.

use Doctrine\Common\EventSubscriber;

class FooSubscriber implements EventSubscriber
{

/**
     * @return array
     */
    public function getSubscribedEvents()
    {
        return [
            'postSoftDelete'
        ];
    }

    /**
     * @param LifecycleEventArgs $args
     */
    public function postSoftDelete(LifecycleEventArgs $args)
    {
        $entity = $args->getEntity():
        // do something
    }

}

Another event is also available: preSoftDelete

After dispatching the postSoftDelete, another Event will be dispatched.

In general, the soft delete is considered as an update query which will generate to dispatch all Events related to the update (preUpdate and postUpdate) .

Leave a Reply

Your email address will not be published. Required fields are marked *