New in Symfony 5.3: Inlined Serialization Context

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 SerializerContext
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
14
use SymfonyComponentSerializerAnnotation as Serializer;
use SymfonyComponentSerializerNormalizerDateTimeNormalizer;

class SomeClass
{
/**
* @SerializerContext({ DateTimeNormalizer::FORMAT_KEY = ‚Y-m-d‘ })
*/
public DateTime $date;

// In PHP 8 applications you can use PHP attributes instead:
#[SerializerContext([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
#[SerializerContext(
normalizationContext: [DateTimeNormalizer::FORMAT_KEY => ‚Y-m-d‘],
denormalizationContext: [DateTimeNormalizer::FORMAT_KEY => DateTime::COOKIE]
)]
public DateTime $date;

#[SerializerContext(
normalizationContext: [DateTimeNormalizer::FORMAT_KEY => DateTime::RFC3339],
groups: [‚extended‘]
)]
public DateTime $date;

Sponsor the Symfony project.

Symfony Blog
Read More

Latest News

PHP-Releases

PHP 8.4.1 released!

PHP 8.1.31 released!

PHP 8.3.14 released!

PHP 8.2.26 released!

Generated by Feedzy