You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

API Platform:PUT处理器如何返回数组字段而非整个对象?

解决API Platform中Patch操作处理器返回数组报错的问题

问题背景

我在API Platform中定义了如下Patch操作:

new Patch(
    uriTemplate: '/account/{id}/info',
    openapiContext: [
        'description' => 'Update the account items',
    ],
    denormalizationContext: ['groups' => ['AccountInfo:write']],
    input: AccountItemsDTO::class,
    processor: AccountInformationStateProcessor::class
);

希望在AccountInformationStateProcessor的process方法中返回数组字段作为响应,而非整个对象,代码如下:

public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): array
{
    // ... 业务逻辑处理

    $arrayResponse = array_values($this->manager->getInformationArray($account));

    return $arrayResponse;
}

但此时出现错误:

Argument #1 ($object) must be of type object, array given

我希望复用处理器中已定义的、能返回格式化数据的方法,因此不想在output属性中使用DTO,请问该如何解决?

解决方案

方法一:配置操作的output为数组类型

在Patch操作定义中添加output参数声明输出为数组类型,同时可按需配置序列化上下文:

new Patch(
    uriTemplate: '/account/{id}/info',
    openapiContext: [
        'description' => 'Update the account items',
    ],
    denormalizationContext: ['groups' => ['AccountInfo:write']],
    input: AccountItemsDTO::class,
    processor: AccountInformationStateProcessor::class,
    output: ['class' => 'array'], // 指定输出为数组
    normalizationContext: ['skip_null_values' => true] // 可选,自定义序列化规则
);

配置后API Platform会接受处理器返回的数组作为响应,不再抛出类型错误。

方法二:用ArrayObject包装数组返回

如果不想修改操作配置,可以将处理器返回的数组包装为PHP内置的ArrayObject(它是对象类型,同时支持数组式访问),既满足API Platform对返回值的类型要求,又能复用现有数组格式化逻辑:

use ArrayObject;

public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): ArrayObject
{
    // ... 业务逻辑处理

    $arrayResponse = array_values($this->manager->getInformationArray($account));

    return new ArrayObject($arrayResponse);
}

序列化器会自动将ArrayObject序列化为数组格式的响应,效果和直接返回数组一致。

内容的提问来源于stack exchange,提问作者Filip Stojanovic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 03:42:21