Contributed by Maxime Steinhausser in #39399.
The Serializer component provides a mechanism to configure the way data is serialized/deserialized: the context options. These options are passed as an optional argument of the serialize/deserialize methods. In Symfony 5.3 we’ve improved the serializer so you can define the context as part of the mapping information thanks to a new Serializer\Context annotation/attribute. For example, to define how some datetime property should be formatted, use the following: 1 2 3 4 5 6 7 8 9 10 11 12 13 14use Symfony\Component\Serializer\Annotation as Serializer; use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer;
class SomeClass { /**
-
@Serializer\Context({ DateTimeNormalizer::FORMAT_KEY = 'Y-m-d' }) */ public \DateTime $date;
// In PHP 8 applications you can use PHP attributes instead:
[Serializer\Context([DateTimeNormalizer::FORMAT_KEY => 'Y-m-d'])]
public \DateTime $date; }
The annotation/attribute supports different contexts for normalization/denormalization and it can also define serialization groups: 1 2 3 4 5 6 7 8 9 10 11#[Serializer\Context( normalizationContext: [DateTimeNormalizer::FORMAT_KEY => 'Y-m-d'], denormalizationContext: [DateTimeNormalizer::FORMAT_KEY => \DateTime::COOKIE] )] public \DateTime $date;
[Serializer\Context(
normalizationContext: [DateTimeNormalizer::FORMAT_KEY => \DateTime::RFC3339],
groups: ['extended']
)] public \DateTime $date;
Sponsor the Symfony project.
Login to add comment
Other posts in this group

Contributed by Yonel Ceruto in

This week, Symfony 6.4.21 and 7.2.6 maintenance versions were released. In addition, we published the first beta of Symfony 7.3 so you can test it in your own apps before its final release at the end

Symfony 7.2.6 has just been released. Here is the list of the most important changes since 7.2.5:
bug #60288 [VarExporter] dump default value for property hooks if present (@xabbuh)
bug #60267 [C

Symfony 7.3.0-BETA1 has just been released. Here is the list of the most important changes since 7.2:
feature #60232 Add PHP config support for routing (@fabpot)
feature #60102 [HttpFoundation] A

SymfonyOnline June 2025 is almost here, starting in almost 2 months on:
June 10-11: Workshop days. It is possible to attend 1 two-day training or 2 one-day trainings. June 12-13: Online confe

Contributed by Kevin Bond in

Symfony 6.4.21 has just been released. Here is the list of the most important changes since 6.4.20:
bug #60288 [VarExporter] dump default value for property hooks if present (@xabbuh)
bug #60268