代码之家  ›  专栏  ›  技术社区  ›  alvery

Symfony API平台自定义删除操作触发默认删除事件

  •  0
  • alvery  · 技术社区  · 8 年前

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

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

    0 回复  |  直到 8 年前
        1
  •  1
  •   Mustapha GHLISSI    7 年前

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