如何在不使用注释的情况下为自定义 DTO 操作配置标识符?

yiv*_*ivi -4 php symfony api-platform.com

基于 DTO 创建了一个非常简单的资源。所有逻辑都将通过自定义提供DataProvider,并且该项目不使用注释。

资源的配置是:

<resources xmlns="https://api-platform.com/schema/metadata">
    <resource class="App\Domain\Dto\ProductUpgradePrice">

        <collectionOperations>
            <collectionOperation name="get"/>
        </collectionOperations>

        <itemOperations>
            <itemOperation name="get"/>
        </itemOperations>

    </resource>
</resources>
Run Code Online (Sandbox Code Playgroud)

实际的DTO是:

<?php declare(strict_types=1);

namespace App\Domain\Dto;

/** @psalm-immutable */
class ProductUpgradePrice
{

    public function __construct(
        public string $productId,
        public int $regularPrice,
        public int $upgradePrice
    ) {}

}
Run Code Online (Sandbox Code Playgroud)

当我尝试时,GET /api/product_upgrade_prices我得到:

没有为 App\Domain\Dto\ProductUpgradePrice 类型的资源定义标识符

这是有道理的。

文档提到使用注释@ApiProperty但正如我之前提到的,这个项目没有注释。(自从我发布问题以来,我提交了一个 PR 来更新文档,该问题已合并,所以希望未来的用户不会遇到同样的情况)

我尝试将其添加到资源配置中:

<property name="productId">
    <attribute name="identifier">true</attribute>
</property>
Run Code Online (Sandbox Code Playgroud)

但得到了相同的结果。

在不使用注释的情况下如何配置它?

小智 5

查看元数据 XSD ,在第113行中,您可以看到该property元素的此属性:

<xsd:attribute type="xsd:boolean" name="identifier"/>
Run Code Online (Sandbox Code Playgroud)

这意味着你应该使用它:

<property identifier="true" name="id" />
Run Code Online (Sandbox Code Playgroud)