Symfony 防止使用监听器对实体进行操作

问题描述 投票:0回答:1

我正在尝试实现 SoftDelete。是的,我知道 Gedmo。

我正在尝试实现以下逻辑,以设置软删除值而不是删除实体:

#[AsDoctrineListener(Events::preRemove)]
class SoftDeleteEventListener
{
    public function preRemove(PreRemoveEventArgs $args): void
    {
        $entityManager = $args->getObjectManager();
        $entity = $args->getObject();
        $reflection = new \ReflectionClass($entity);
        $traits = $reflection->getTraitNames();

        if (in_array(SoftDeleteTrait::class, $traits)) {
            $entity->setDeletedAt(new \DateTimeImmutable());
            // cancel the deletion and persist the entity
            return;
        }
        
        // Go with the usual flow, flush
    }
}

上述代码导致实体删除。

我正在使用 API 平台,因此我正在为所有实体寻找统一的逻辑,而不必在自定义控制器中实现它。

我正在使用 Symfony 7。

谢谢你

php symfony doctrine-orm doctrine api-platform.com
1个回答
0
投票

我最终使用了 API 平台状态处理器:

class SoftDeleteStateProcessor implements ProcessorInterface
{
    public function __construct(private readonly EntityManagerInterface $entityManager)
    {}

    public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): void
    {
        $data->setDeletedAt(new \DateTimeImmutable());
        $this->entityManager->persist($data);
        $this->entityManager->flush();
    }
}

缺点是我必须在每个实体上指定此处理器,但这是我愿意做出的权衡。

© www.soinside.com 2019 - 2024. All rights reserved.