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.
Nice one!!! Thanks!
Every so often one of these features announced is one of those that is just a straight up truly amazing things that I always wanted a way to do. This is one of them!
Really nice!!! good job 👏
🤓
If I understand the example, we can also have different contexts using group?