Converting an array into an object with the Symfony serializer

Published on 2023-04-13 • Modified on 2023-04-13

This snippet shows how to convert an array into an object with the Symfony serializer. That's a common need to denormalize an array into an object. The documentation is not clear on this subject. We must use the serializer service already configured for the most common cases.
Something that seems weird at first is that we get the serializer with the help of the Symfony\Component\Serializer\SerializerInterface, but if you look at the contract, there is no denormalize() function. It is only present in the concrete implementation, the Symfony\Component\Serializer\Serializer class. That's why I annotate the property with SerializerInterface&Serializer to indicate that the object is both a SerializerInterface and a Serializer.
With the default setup, the serializer can denormalize an object with getters/setters and an object with public properties.
In the first example, the ValueObject class has a getFoo() getter and a setFoo() setter.
In the second example, the ValueObjectPublicProperties class as a public property foo.


<?php

declare(strict_types=1);

namespace App\Controller\Snippet;

use App\Dto\ValueObject;
use App\Dto\ValueObjectPublicProperties;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\SerializerInterface;

/**
 * I am using a PHP trait to isolate each snippet in a file.
 * This code should be called from a Symfony controller extending AbstractController (as of Symfony 4.2)
 * or Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
 * Services are injected in the main controller constructor.
 *
 * @property SerializerInterface&Serializer $serializer
 */
trait Snippet251Trait
{
    public function snippet251(): void
    {
        $array = [
            'foo' => 'bar',
        ];

        $dto = $this->serializer->denormalize($array, ValueObject::class);
        $dto2 = $this->serializer->denormalize($array, ValueObjectPublicProperties::class);

        var_dump($dto);
        var_dump($dto2);

        // That's it! 😁
    }
}

 Run this snippet  More on Stackoverflow   Read the doc  More on the web  Random snippet

  Work with me!