Symfony ApiPlatform自定义DELETE操作触发默认的remove事件

时间:2018-09-24 13:40:00

标签: symfony api-platform.com

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

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

因此,即使我在控制器中编写了自己的逻辑,也总是会触发我的实体在api平台事件系统中将其删除。如何防止这种行为?

1 个答案:

答案 0 :(得分:0)

您可以实现一个实现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
    }

}