How to use "paramconverter with API-Platform?

流过昼夜 提交于 2020-01-03 02:00:07

问题


How to implement or use paramconverter with Symfony API platform?

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

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

回答1:


Why not use a decorator?

E.g. if your controller is something like:

class IndexController {

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

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


来源:https://stackoverflow.com/questions/56112903/how-to-use-paramconverter-with-api-platform

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!