DTOs Instead of the Entity Directly
DTOs Instead of the Entity Directly
~15 Min. Lesezeit Zuletzt aktualisiert am August 8, 2026
Serialization groups suffice for MOST cases – sometimes, though, the API response format needs to STRUCTURALLY differ from the entity's shape. That's what DTOs (Data Transfer Objects) are for.
When groups are no longer enough
- The API response should COMBINE fields from MULTIPLE entities (e.g. a project + task count in ONE flat object).
- The external API format should stay INDEPENDENT of internal entity refactorings (versioning/stability).
- The computation logic is too COMPLEX for a single getter method (chapter 25) and deserves its OWN class.
Defining an output DTO
<?php
declare(strict_types=1);
namespace App\Dto;
final class ProjectSummary
{
public int $id;
public string $name;
public bool $isRecent;
}A SIMPLE, plain data class WITHOUT Doctrine attributes, WITHOUT validation – a DTO describes ONLY the SHAPE of the API response, not persistence.
Binding the DTO to an operation
use App\Dto\ProjectSummary;
new Get(
uriTemplate: '/projects/{id}/summary',
output: ProjectSummary::class,
provider: ProjectSummaryProvider::class,
),output determines WHICH class API Platform serializes instead of the entity – a provider (a STATE PROVIDER, EXACTLY the principle from chapter 5) handles the actual POPULATING of the DTO from the real Project entity.
Achtung: A COMPLETE provider example follows ONLY in block 7 (chapters 57-66), once state providers are covered in DETAIL – this chapter conveys ONLY the CONCEPT, so later chapters can build on it WITHOUT re-explaining the principle.
DTOs vs. groups: a decision guide
| Approach | When it makes sense |
|---|---|
| Serialization groups (chapters 23-24) | SIMPLER, directly on the entity, sufficient for MOST CRUD cases |
| DTOs (this chapter) | MORE effort, but necessary for combined/heavily divergent response formats |
Tipp: For OUR project, Project and Tag stick with serialization groups – DTOs come into play ONLY in block 7, once a project statistics resource offers REAL added value over a plain entity response.