DTO in Symfony: an object for incoming data

A DTO, in Symfony, is a small class with no link to the database that describes and validates incoming data, from an API's JSON as well as from a form.

final readonly class ReservationDemande
{
    public function __construct(
        #[Assert\NotBlank(message: 'Enter your name.')]
        public string $nom = '',

        #[Assert\Range(min: 1, max: 12)]
        public int $personnes = 0,

        #[Assert\NotNull(message: 'Enter the day of your visit.')]
        #[Assert\GreaterThanOrEqual('today')]
        public ?\DateTimeImmutable $jour = null,
    ) {
    }
}

The request is not the entity: the DTO only carries what the client is allowed to send, never an id or a creation date, and its constraints apply to the input, not to storage. The controller receives it filled in and validated, then builds the entity itself. Its default values matter: a field missing from the JSON gets '' or 0 and hits a rule with a clear message. The trap: promising a non-nullable type without a default value. A missing field never reaches validation, it fails as soon as the object is built, and the error returned talks about types instead of saying what is missing.

The exercises have you write the DTO for bookings sent by magic pigeon, received through #[MapRequestPayload], then, in Symfony 8.2, declare a contact form directly on its DTO with #[AsFormType] and #[FormField].

3 exercises work on this concept, by writing code in the browser.

In the tracks

In Practice

Related concepts

Forms#[MapRequestPayload]