如何将“ paramconverter与API平台一起使用?

时间:2019-05-13 13:00:35

标签: php symfony parameters api-platform.com

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

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

我没有在该项目上使用注释。路由配置位于YAML文件中。

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

1 个答案:

答案 0 :(得分:2)

为什么不使用decorator

例如如果您的控制器是这样的:

class IndexController {

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

您可以构建装饰器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); 

     }
}

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

services:
    App\Controller\IndexController: ~

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