admin管理员组

文章数量:1391977

I'm working on a project that uses API Platform 4 to implement a REST API, but it doesn't have a database and no Doctrine ORM.

I'm trying to implement an ApiResource that, among other properties, expects a list of objects:

#[ApiPlatform\Metadata\ApiResource(
    operations: [new ApiPlatform\Metadata\Post()],
    processor: App\State\OrderProcessor::class,
)]
class Order
{
    /** @var Product[] */
    #[Symfony\Component\Validator\Constraints\Valid]
    public array $products = [];
}

class Product
{
    public string $name = '';
}

But when accessing Order::$products in my Processor, it's not a list of Product objects, but an associative array of whatever was provided as products in the HTTP payload:

/**
 * @implements ApiPlatform\State\ProcessorInterface<App\ApiResource\Order, App\ApiResource\Order|void>
 */
final class OrderProcessor implements ApiPlatform\State\ProcessorInterface
{
    /**
     * @return App\ApiResource\Order
     */
    public function process(
        mixed $order,
        ApiPlatform\Metadata\Operation $operation,
        array $uriVariables = [],
        array $context = [],
    ): mixed {
        // $order->products is array[] with whatever was passed in the
        // HTTP payload instead of Product[].

        return $order;
    }
}

API Platform doesn't seem to know to what object $product should be hydrated onto, probably because it doesn't read the @var annotation on the property, so it resorts to just unserializing $products. How can I map $products to Product?

Do I need to write a custom normalizer?

I already tried requiring doctrine/collections and using public Doctrine\Common\Collections\ArrayCollection $products, but that just resulted in an empty collection.

本文标签: phpSymfony 7API Platform 4 Hydrate array of objects without Doctrine ORMStack Overflow