Implementing SoftDelete in Symfony with Doctrine
Soft Delete is a technique where records are not physically removed from the database but are instead marked as deleted. This can be useful for auditing and restoring data if needed. In Symfony, we can implement Soft Delete using the Doctrine ORM and the Gedmo Doctrine Extensions. Here’s how you can set it up in your project.
Doctrine Configuration
First, ensure that your doctrine.yaml
file is set up to enable the SoftDeleteable filter:
orm:
filters:
soft_delete:
class: Gedmo\SoftDeleteable\Filter\SoftDeleteableFilter
enabled: true
This configuration enables the SoftDeleteable filter, which allows Doctrine to handle entities marked as deleted.
Doctrine Extensions Configuration
Next, configure the Gedmo extensions in your doctrine_extensions.yaml
file:
services:
gedmo.mapping.driver.attribute:
class: Gedmo\Mapping\Driver\AttributeReader
gedmo.listener.softdeleteable:
class: Gedmo\SoftDeleteable\SoftDeleteableListener
tags:
- { name: doctrine.event_listener, event: 'onFlush' }
- { name: doctrine.event_listener, event: 'loadClassMetadata' }
calls:
- [ setAnnotationReader, [ "@gedmo.mapping.driver.attribute" ] ]
This configuration sets up the Gedmo SoftDeleteable listener, which listens for specific Doctrine events and applies the SoftDeleteable logic.
Entity Setup
In your entity, you need to use the SoftDeleteable trait and annotate the class with #[Gedmo\SoftDeleteable]
:
// src/Entity/Subscriber.php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use Gedmo\SoftDeleteable\Traits\SoftDeleteable;
#[ORM\Entity(repositoryClass: SubscriberRepository::class)]
#[Gedmo\SoftDeleteable]
class Subscriber
{
use SoftDeleteable;
// Other properties and methods
}
The SoftDeleteable trait adds the necessary properties and methods to handle soft deletes.
Controller
Here is an example of a controller method to soft delete a Subscriber
entity:
#[Route(path: '/delete/subscriber/{id:id}', name: 'delete_subscriber', methods: ['DELETE'])]
public function deleteSubscriber(
Subscriber $subscriber,
EntityManagerInterface $manager
): JsonResponse {
$manager->remove($subscriber);
$manager->flush();
return new JsonResponse(status: Response::HTTP_NO_CONTENT);
}
In this method, when a Subscriber
is deleted, it is marked as deleted rather than being removed from the database.
Disabling the SoftDeleteable Filter
To access entities that are marked as deleted, you can disable the SoftDeleteable filter in your Doctrine queries. This can be useful for administrative tasks or when you need to audit deleted records.
$manager->getFilters()->disable('soft_delete');
Conclusion
By following these steps, you can implement SoftDelete in your Symfony project using Doctrine and the Gedmo Doctrine Extensions. This allows you to maintain records in your database for auditing and potential recovery, while also preventing them from being returned in normal queries.