Skip to content

JSON and frameworks ​

Out: nothing to do ​

Collections implement JsonSerializable: json_encode($users) gives a JSON list, a map with string or int keys gives an object. serialize() works too, maps keep object keys, and unserialize() checks the data like the constructor does, so a payload from a cache or a queue cannot smuggle in a wrong element.

In: a mapper builds the elements ​

json_decode() gives arrays. Turning them into User objects is a mapper's job, as for any typed array. Pick one:

Valinor ​

Valinor reads @extends ImmutableList<User> and builds collections, nested ones included, with no configuration.

Symfony Serializer ​

Symfony cannot build collection objects on its own: ObjectNormalizer reads a JSON list as properties and returns an empty collection. Install the bridge:

bash
composer require eugeneerg/collections-symfony
yaml
# config/services.yaml
services:
    EugeneErg\Collections\Symfony\Serializer\CollectionDenormalizer: ~

Collections then work as the root type, as typed DTO properties and in #[MapRequestPayload]; elements go through your other normalizers (enums, dates, objects), errors come with a path, and dump() shows the elements. Details on the package page.

Anything else: Hydrator ​

Hydrator walks raw data, builds nested collections itself, and gives every other element to your callback with the type the collection expects and its path:

php
$teams = Hydrator::hydrate(
    Teams::class,                       // ImmutableMap<string, Users>
    json_decode($json, true),
    fn(mixed $raw, Type $type, string $path) => $type instanceof InstanceOfType && $type->class === User::class
        ? new User($raw['name'])
        : $raw,
    'teams',                            // errors say "teams[red][0] ..."
);

Writing your own bridge ​

CollectionShape tells what a class holds:

php
$shape = CollectionShape::of(Users::class);
$shape->kind;       // CollectionKind::List, Map or Set
$shape->valueType;  // InstanceOfType: User
$shape->keyType;    // maps only
CollectionShape::isCollection($class);

With Hydrator for the walking, a bridge for another framework is a few dozen lines; the Symfony one is a good template.