如何在 API-Platform 中使用“paramconverter"? [英] How to use "paramconverter with API-Platform?

查看:46
本文介绍了如何在 API-Platform 中使用“paramconverter"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Symfony API 平台上实现或使用 paramconverter?

How to implement or use paramconverter with Symfony API platform?

我想在路由上使用实体 ID 并立即生成一个对象,准备在控制器中使用.

I want to use entity ID on the route and generate immediately an object, ready to be used in the controller.

我没有在这个项目中使用注释.路由配置在 YAML 文件中.

I'm not using annotations on this project. Route configurations are in the YAML file.

resources:
    App\Meetings\Domain\Entity\Meeting:
        collectionOperations:
            invitation_response:
                method: 'POST'
                path: 'users/{id}'
                controller: 'App\Controller\User\IndexController'
                defaults:
                    _api_receive: false

推荐答案

为什么不使用 装饰器?

例如如果您的控制器类似于:

E.g. if your controller is something like:

class IndexController {

   public function __invoke(CustomClass $object) {
      // do your thing
      // return a Response
   }

你可以构建一个装饰器 CustomClassConverterController

You could build a decorator CustomClassConverterController

class CustomClassConverter {

     protected $innerController;
     protected $em;

     public function (IndexController $controller, EntityManagerInterface $em) {
        $this->innerController = $controller;
        $this->em = $em;
     }

     public function __invoke($id) {

        $object = $this->em->getRepository(CustomClass::class)->findOne((int) $id);
        if (! $object instanceof CustomClass) {
           throw new NotFoundHttpException('Custom class ' . $id . ' not found');
        }

        return $this->innerController($object); 

     }
}

您需要添加此配置以激活装饰:

You'd need to add this configuration to activate the decoration:

services:
    App\Controller\IndexController: ~

    App\Decorator\CustomClassConverterController:
        decorates: App\Controller\IndexController

这篇关于如何在 API-Platform 中使用“paramconverter"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆