Skolem IRI 用于使用 DTO 更改输出响应的实体

问题描述 投票:0回答:1

我使用的是API平台v3.1.14

我正在使用 DTO 返回实体的自定义输出。然而,它生成的是 skolem iri 而不是实体。

我已经尝试了DTO Api Platform v3中的建议 和https://github.com/api-platform/core/issues/5451 但它不起作用。

实体:

<?php

namespace App\Entity;

use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Get;
use Doctrine\ORM\Mapping as ORM;
use App\Repository\KeyRepository;
use App\Dto\KeyOutput;
use App\State\KeyOutputProvider;
use ApiPlatform\Metadata\Post;

#[ApiResource(
    shortName: 'Key_new',
        operations: [
                new Post(),
        ],
)]
#[Get(
    uriTemplate: '/keys_new/{id}',
    shortName: 'Key_new',
    output: KeyOutput::class,
    provider: KeyOutputProvider::class,
    openapi: true,
  )]
#[ORM\Entity(repositoryClass: KeyRepository::class)]
class KeyNew {

    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column]
    public ?int $id = null;

    #[ORM\Column(length: 255)]
    private ?string $title = null;

    public function getId(): int
    {
        return $this->id;
    }

    public function getTitle(): ?string
    {
        return $this->title;
    }

    public function setTitle(string $title): self
    {
        $this->title = $title;

        return $this;
    }
}

DTO:

<?php

namespace App\Dto;
use App\State\KeyOutputProvider;
use ApiPlatform\Metadata\Get;


class KeyOutput
{
    public int $id;

    public string $title;
}


国家提供者:

<?php

namespace App\State;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\Dto\KeyOutput;
use App\Repository\KeyRepository;

final class KeyOutputProvider implements ProviderInterface
{
  public function __construct(private ProviderInterface $itemProvider, private KeyRepository $keyRepository)
  {
  }

    /**
     * {@inheritDoc}
     */
    public function provide(Operation $operation, array $uriVariables = [], array $context = []) : object | array
    {
      $key =  $this->keyRepository->find($uriVariables['id']);

      $output = new KeyOutput();
      $output->id = $key->getId();
      $output->title = $key->getTitle();
      return $output;
    }

  }

尝试过: DTO API 平台 v3 https://github.com/api-platform/core/issues/5451

仍为 @id 生成 Skolem Uri。

我的事件尝试将 GET 操作放在 DTO 上,但无法识别。

php api symfony api-platform.com platform
1个回答
0
投票

如所述:https://github.com/api-platform/core/issues/5451#issuecomment-1464902089

您可以使用与实体中相同的短名称的属性来标记您的 DTO。所以你的 DTO:

#[Get(shortName: 'Key_new')]
class KeyOutput{...

和实体:

#[ApiResource(
    shortName: 'Key_new',
        operations: [
                new Post(),
        ], )]
#[Get(
    uriTemplate: '/keys_new/{id}',
    shortName: 'Key_new',
    output: KeyOutput::class,
    provider: KeyOutputProvider::class,
    openapi: true,   )]
#[ORM\Entity(repositoryClass: KeyRepository::class)] 
class KeyNew {

但我认为最好的选择是将您的 DTO 标记为 ApiResource,并保留没有 ApiResource 属性的实体。不幸的是,我不知道将 DTO 和实体标记为 ApiResource 可能会发生任何问题。

© www.soinside.com 2019 - 2024. All rights reserved.