New in Symfony 6.4: Class-based Serializer Contexts
October 27, 2023 • Published by Javier Eguiluz
Symfony 6.4 is backed by:
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
namespace App\Model;
use Symfony\Component\Serializer\Annotation\Context;
use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer;
#[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.
Help the Symfony project!
As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.
Comments are closed.
To ensure that comments stay relevant, they are closed for old posts.