phpsymfony

How to Map an Array of JSON Objects to an Array of DTOs Using MapRequestPayload


I'm working with Symfony and have an incoming JSON payload that looks like this:

[
    {
        "number": 1,
        "description": "Test 1"
    },
    {
        "number": 2,
        "description": "Test 2"
    },
   {
        "number": 3,
        "description": "Test 3"
    }
]

I have a Data Transfer Object (DTO) defined like this:

<?php

class MyDto {

 public function __constructor(
   public readonly int $number,
   public readonly int $description,
 ) {}
}

My goal is to map the array of JSON objects directly to an array of MyDto objects in my Symfony controller. Here's my current controller method:

public funtion index(#[MapRequestPayload] MyDto $dto) {
    ...
}

I'm trying to find a way to map the array of JSON objects to an array of MyDto objects without needing to create another DTO to wrap this data under a key. Is there a built-in or efficient way to do this in Symfony?


Solution

  • Since Symfony 7.1, there is a new argument on MapRequestPayload attribute which allows you to type hint your controller argument with array, and specify the DTOs you expect :

    public funtion index(#[MapRequestPayload(type: MyDto::class)] array $dtos) {
        ...
    }
    

    cf. https://github.com/symfony/symfony/commit/3f721434062045c1bad7849d1b412d07aa2b98e4