Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 62 ยท Routing and Controllers

Mapping Request Data to Objects

Turn query strings and JSON bodies into typed DTO objects with #[MapQueryString] and #[MapRequestPayload], validate them, and see the mechanism in a runnable stand-in.

Reading $request->query->get('page') or json_decode($request->getContent()) by hand works, but it scatters string handling, type casting and validation across every controller. Symfony can do that boring work for you: you describe the data you expect as a small class, put an attribute on a controller argument, and Symfony builds the object from the request before your method runs. If the data is wrong, your controller never executes.

This lesson shows the two attributes that do this, #[MapQueryString] and #[MapRequestPayload], explains how they combine the Serializer and Validator components, and then rebuilds the mechanism in plain PHP so you can watch it work. You should already know how the request object and controllers work.

The idea: a DTO per request

A DTO (data transfer object) is a plain class whose only job is to carry data: no database, no behaviour beyond maybe a helper or two. For a product search page, the DTO describes the allowed query parameters. For a "create product" endpoint, it describes the JSON body.

PHP
// src/Dto/ProductSearch.php (real Symfony, read-only)
namespace App\Dto;

use Symfony\Component\Validator\Constraints as Assert;

final class ProductSearch
{
    public function __construct(
        #[Assert\Length(max: 60)]
        public readonly string $term = '',

        #[Assert\Positive]
        public readonly int $page = 1,

        public readonly bool $inStock = false,
    ) {
    }
}

The constructor parameters give you three things at once: the names of the accepted fields, their types, and their defaults. Constraint attributes on the parameters add rules. The rest is wiring.

MapQueryString

#[MapQueryString] fills a DTO from the query string (the part after ?).

PHP
// src/Controller/ProductController.php (real Symfony, read-only)
namespace App\Controller;

use App\Dto\ProductSearch;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Attribute\MapQueryString;
use Symfony\Component\Routing\Attribute\Route;

final class ProductController
{
    #[Route('/products', name: 'product_index')]
    public function index(#[MapQueryString] ProductSearch $search): Response
    {
        return new Response(sprintf(
            'Searching "%s", page %d',
            $search->term,
            $search->page,
        ));
    }
}

A request to /products?term=lamp&page=2 produces a ProductSearch with term set to lamp and page set to 2 (an integer, not the string "2"). Query values always arrive as strings, so Symfony's argument resolver denormalizes them with the Serializer in a mode that accepts numeric strings for typed properties.

If the argument is nullable, or has a default value (?ProductSearch $search = null), a request with an empty query string gives you null or the default instead of an error.

MapRequestPayload

#[MapRequestPayload] maps the request body. It looks at the Content-Type header and picks a decoder: JSON and XML bodies go through the Serializer, and form-encoded bodies are mapped from the submitted fields.

PHP
// src/Dto/CreateProduct.php (real Symfony, read-only)
namespace App\Dto;

use Symfony\Component\Validator\Constraints as Assert;

final class CreateProduct
{
    public function __construct(
        #[Assert\NotBlank]
        #[Assert\Length(min: 3, max: 80)]
        public readonly string $name,

        #[Assert\PositiveOrZero]
        public readonly int $priceInCents,

        #[Assert\Email]
        public readonly ?string $contactEmail = null,
    ) {
    }
}
PHP
// src/Controller/ProductApiController.php (real Symfony, read-only)
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Attribute\MapRequestPayload;
use Symfony\Component\Routing\Attribute\Route;

final class ProductApiController
{
    #[Route('/api/products', methods: ['POST'])]
    public function create(#[MapRequestPayload] CreateProduct $input): JsonResponse
    {
        // $input is already built and validated here.
        return new JsonResponse(['name' => $input->name], 201);
    }
}

Both attributes live in the HttpKernel component, but they need two other packages installed: symfony/serializer to build the object and symfony/validator to check it. Without the validator, mapping still works but constraints are ignored.

flowchart LR
    R["Request"] --> A["Argument resolver<br/>(sees #[MapRequestPayload])"]
    A --> D["Serializer<br/>decode and denormalize"]
    D --> V["Validator<br/>check constraints"]
    V -->|valid| C["Controller runs<br/>with typed DTO"]
    V -->|violations| E["Exception to HTTP error<br/>controller never runs"]

The argument resolver turns the request into a DTO and validates it before the controller is called.

What happens when the data is wrong

Mapping can fail in two ways:

  • Malformed or mistyped input. A body that is not valid JSON, a missing required constructor argument, or a value of the wrong type ("abc" for an int).
  • Constraint violations. The data has the right shape but breaks a rule such as Length(min: 3).

In both cases the resolver throws an HTTP exception before your controller runs. Validation failures carry the full list of violations as a previous exception, and Symfony's error handling turns them into a response. With the Serializer's problem-details support installed, an API client receives a structured error body listing each field. Both attributes accept a validationFailedStatusCode option, so you can choose the status code (422 Unprocessable Content is the usual choice for APIs) rather than relying on the default, which can differ between attributes and versions.

Other options you will meet often:

  • validationGroups: run only constraints in some validation groups.
  • serializationContext: pass extra context to the Serializer, for example to forbid unknown fields.
  • acceptFormat on #[MapRequestPayload]: restrict the body to json or xml.
  • resolver: use your own value resolver class for special cases.

Do not map straight onto a Doctrine entity from user input. A DTO limits exactly which fields a client can set; mapping to an entity makes every property settable and invites mass-assignment bugs. Map to a DTO, validate it, then copy the values you want onto the entity.

A stand-in you can run

The real attributes need Composer packages, so here is a plain-PHP stand-in of the first half: reading a constructor with reflection, picking the right value for each parameter, casting it to the declared type, and falling back to defaults. It is not Symfony's code, but it follows the same idea.

PHP Mapping a query string to a DTO (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Notice that page ends up as the integer 2 in the JSON output, that defaults fill the gaps, and that the bad value stops the mapping with a clear message. Symfony does the same in spirit, but with the Serializer's much richer type handling: nested objects, enums, dates and arrays.

Validation on top of mapping

The second half of the job is validation. In real Symfony you simply write constraint attributes. The stand-in below implements the same pattern at toy scale: constraint classes are attributes, a validator reads them with reflection, and a mapper returns either a valid object or a list of violations with a 422 status.

PHP Payload mapping with validation (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The output shows the three outcomes: a valid object, a 422 with one message per bad field, and a 400 for a body that is not JSON. Real Symfony reports every violation (including several per field) in a structured error, but the control flow is the same: map, validate, then either run the controller or answer with an error.

Choosing between attributes and manual reading

Use #[MapQueryString] for filters, sorting and pagination, where an invalid value should not reach the controller. Use #[MapRequestPayload] for JSON APIs and simple form posts. For full HTML forms with CSRF tokens, error rendering and re-display of submitted values, the Form component is still the better tool. And for single values such as ?page=2, #[MapQueryParameter] int $page = 1 on a controller argument is lighter than a whole DTO.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does #[MapRequestPayload] do on a controller argument?

    The argument resolver decodes the body, builds the DTO and validates it. Your controller only runs if that succeeds.
  2. 2. Which two packages do the mapping attributes rely on to build and check the object?

    The Serializer denormalizes the data into the object and the Validator checks the constraint attributes.
  3. 3. Why is a DTO safer than mapping request data directly onto a Doctrine entity?

    A DTO lists exactly the accepted fields. Mapping to an entity can let a client set properties such as roles or ids.
  4. 4. A query value like page=2 arrives as a string. How does the DTO end up with an int?

    Query data is always text. The resolver uses the Serializer, which reads the declared type and converts the value.

Summary

  • A DTO is a plain class that describes the data a request may carry; constructor types and defaults define fields.
  • #[MapQueryString] fills a DTO from the query string; #[MapRequestPayload] fills it from the body (JSON, XML or form data).
  • Mapping needs symfony/serializer; constraint attributes need symfony/validator.
  • On bad input the controller never runs: Symfony throws an HTTP exception, and you can pick the status with validationFailedStatusCode.
  • Map to DTOs, not entities, and copy validated values onto your entities yourself.

Next up: Sessions and Flash Messages.