Symfony ApiPlatform自定义DELETE操作触发默认删除事件

68bkxrlz  于 2022-11-25  发布在  其他
关注(0)|答案(2)|浏览(119)

我有一个关于API平台自定义路由功能的问题。当尝试使用DELETE方法实现自定义路由时,事件系统会为http请求中的对象触发(由param转换器找到):

* @ApiResource(
*     attributes={
*         "normalization_context": {
*         },
*         "denormalization_context": {
*         },
*     },
*     itemOperations={
*     },
*     collectionOperations={
*         "customObjectRemove": {
*             "method": "DELETE",
*             "path": "/objects/{id}/custom_remove",
*             "controller": CustomObjectRemoveController::class,

所以,即使我已经在控制器中编写了自己的逻辑,我的实体也总是在api平台事件系统中被触发删除。我该如何防止这种行为呢?

wyyhbhjk

wyyhbhjk1#

您可以实现一个实现EventSubscriberInterface的事件订阅者:

<?php 
namespace App\EventSubscriber;

use ApiPlatform\Core\EventListener\EventPriorities;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent;
use Symfony\Component\HttpKernel\KernelEvents;

final class DeleteEntityNameSubscriber implements EventSubscriberInterface
{

    public function __construct()
    {
        // Inject the services you need
    }

    public static function getSubscribedEvents()
    {
        return [
            KernelEvents::VIEW => ['onDeleteAction', EventPriorities::PRE_WRITE]
        ];
    }

    public function onDeleteAction(GetResponseForControllerResultEvent $event)
    {
        $object = $event->getControllerResult();
        $request = $event->getRequest();
        $method = $request->getMethod();

        if (!$object instanceof MyEntity || Request::METHOD_DELETE !== $method) {
            return;
        }

       // Do you staff here
    }

}
ni65a41a

ni65a41a2#

我知道这个问题是相当古老的,但它出现在谷歌结果。
您可以通过添加write: false(禁用端点的自动删除和刷新功能)将路由配置为不删除实体:

collectionOperations={
 *         "customObjectRemove": {
 *             "method": "DELETE",
 *             "path": "/objects/{id}/custom_remove",
 *             "controller": CustomObjectRemoveController::class,
 *             "write": false

注意:您需要在事件订阅者中添加flush,否则将不保存更改。

相关问题