New in Symfony 6.4: Class-based Serializer Contexts

Contributed by
Mathias Arlaud

in #51476.

The serializer context controls the serialization and deserialization of
resources. This context is passed to all normalizers and can be used for example
to set the date/time format, how to represent empty objects and arrays, etc.

In Symfony you can define that context in multiple ways: as a PHP array passed to
serialize() and deserialize() methods, as a framework.serializer.default_context
global configuration option and via the #[Context] attribute on class properties.

In Symfony 6.4 we’re introducing a new way of setting the serializer context:
using the #[Context] attribute on the class itself:

namespace AppModel;

use SymfonyComponentSerializerAnnotationContext;
use SymfonyComponentSerializerNormalizerDateTimeNormalizer;

#[Context([DateTimeNormalizer::FORMAT_KEY => DateTime::RFC3339])]
#[Context(
context: [DateTimeNormalizer::FORMAT_KEY => DateTime::RFC3339_EXTENDED],
groups: [‚extended‘],
)]
class Person
{
// …
}

The class-based #[Context] attribute is applied to all properties of the class,
which can override that configuration with their own #[Context] attributes.
This new feature will improve DX (developer experience) when working with the
Serializer component and will make you more productive by avoiding repetition.

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