API Platform - Which approach should I use for creating custom operation without entity

前端 未结 1 1163
夕颜
夕颜 2021-02-09 02:51

I\'m new to API Platform. I think it\'s great but I cannot find any example how to create custom endpoint that isn\'t based on any entity. There are a lot of examples based on a

相关标签:
1条回答
  • 2021-02-09 03:31

    You are not forced to use entities. Classes that are marked with @ApiResource annotation may not be entities. Actually, if your application is smarter than basic CRUD you should avoid marking entities as ApiResource.

    Since you want to use POST HTTP method (which is for creating resource items) you can do something like this.

    1) Define class describing search fields and which will be your @ApiResource

    <?php
    // src/ApiResource/Search.php 
    
    namespace App\ApiResource;
    
    use ApiPlatform\Core\Annotation\ApiResource;
    use ApiPlatform\Core\Action\NotFoundAction;
    use ApiPlatform\Core\Annotation\ApiProperty;
    use App\Dto\SearchResult;
    
    /**
     * @ApiResource(
     *     itemOperations={
     *         "get"={
     *             "controller"=NotFoundAction::class,
     *             "read"=true,
     *             "output"=false,
     *         },
     *     },
     *     output=SearchResult::class
     * )
     */
    class Search
    {
        /**
         * @var string
         * @ApiProperty(identifier=true)
         */
        public $from;
    
        /** @var string */
        public $to;
    }
    

    2) Define DTO that will represent the output

    <?php
    // src/Dto/SearchResult.php
    
    namespace App\Dto;
    
    class SearchResult
    {
        public $flights;
        public $airports;
        public $cities;
    }
    

    3) Create class that will inplement DataPersisterInterface for handling business logic. It will be called by framework because you make POST request.

    <?php
    // src/DataPersister/SearchService.php
    
    declare(strict_types=1);
    
    namespace App\DataPersister;
    
    use ApiPlatform\Core\DataPersister\DataPersisterInterface;
    use App\Dto\SearchResult;
    use App\ApiResource\Search;
    
    final class SearchService implements DataPersisterInterface
    {
        public function supports($data): bool
        {
            return $data instanceof Search;
        }
    
        public function persist($data)
        {
            // here you have access to your request via $data
            $output = new SearchResult();
            $output->flights = ['a lot of json data'];
            $output->airports = ['a lot of json data'];
            $output->cities = ['inputData' => $data];
            return $output;
        }
    
        public function remove($data)
        {
            // this method just need to be presented
        }
    }
    

    That way you will recieve results based on request.

    0 讨论(0)
提交回复
热议问题