你应该看看doctrine events with Symfony:
第一步:我用一种方法创建了一个ProtectedInterface接口:
public function isDeletable(): boolean
第 2 步: 我创建了一个 ProtectionTrait 特征,它创建了一个新属性。这个isDeletable 属性用@ORM/Column 注释。该特征实现了 isDeletable()。它只是一个吸气剂。
如果我的实体可能有一些不可删除的数据,我会更新类。我的班级现在将实现我的 DeleteProtectedInterface 并使用我的 ProtectionTrait。
第 3 步:我创建了一个异常,每次有人尝试删除不可删除的实体时都会抛出该异常。
第四步: 提示如下:我创建了一个监听器like the softdeletable。在这个监听器中,当我的实体实现 ProtectedInterface 时,我添加了一个条件测试,我调用 getter isDeleteable():
final class ProtectedDeletableSubscriber implements EventSubscriber
{
public function onFlush(OnFlushEventArgs $onFlushEventArgs): void
{
$entityManager = $onFlushEventArgs->getEntityManager();
$unitOfWork = $entityManager->getUnitOfWork();
foreach ($unitOfWork->getScheduledEntityDeletions() as $entity) {
if ($entity instanceof ProtectedInterface && !$entity->isDeletable()) {
throw new EntityNotDeletableException();
}
}
}
}
我认为这段代码可以优化,因为每次删除实体时都会调用它。在我的应用程序中,用户不会删除很多数据。如果你使用 SoftDeletable 组件,你应该用这个和原来的混合来替换它,以避免大量的测试。例如,您可以这样做:
final class ProtectedSoftDeletableSubscriber implements EventSubscriber
{
public function onFlush(OnFlushEventArgs $onFlushEventArgs): void
{
$entityManager = $onFlushEventArgs->getEntityManager();
$unitOfWork = $entityManager->getUnitOfWork();
foreach ($unitOfWork->getScheduledEntityDeletions() as $entity) {
if ($entity instanceof ProtectedInterface && !$entity->isDeletable()) {
throw new EntityNotDeletableException();
}
if (!$entity instance SoftDeletableInterface) {
return
}
//paste the code of the softdeletable subscriber
}
}
}