piotr712
piotr712

Reputation: 29

How deserialize array in Symfony

I'd like to deserialize array to class in Symfony but I can't find a way to do it without using e.g json or XML.

This is class:

class Product
{
    protected $id;
    protected $name;
    ...
    public function getName(){
    return $this->name;
    }
    ...

} 

Array that I'd like to deserialize to Product class.

$product['id'] = 1;
$product['name'] = "Test";
...

Upvotes: 0

Views: 3698

Answers (2)

qooplmao
qooplmao

Reputation: 17759

You could do it through reflection like this..

function unserialzeArray($className, array $data)
{
    $reflectionClass = new \ReflectionClass($className);
    $object = $reflectionClass->newInstanceWithoutConstructor();

    foreach ($data as $property => $value) {
        if (!$reflectionClass->hasProperty($property)) {
            throw new \Exception(sprintf(
                'Class "%s" does not have property "%s"',
                $className,
                $property
            ));
        }

        $reflectionProperty = $reflectionClass->getProperty($property);
        $reflectionProperty->setAccessible(true);
        $reflectionProperty->setValue($object, $value);
    }

    return $object;
}

Which you would then call like..

$product = unserializeArray(Product::class, array('id' => 1, 'name' => 'Test'));

Upvotes: 1

Paweł Mikołajczuk
Paweł Mikołajczuk

Reputation: 3822

You need to use denormalizer directly.

Version:

class Version
{
    /**
     * Version string.
     *
     * @var string
     */
    protected $version = '0.1.0';

    public function setVersion($version)
    {
        $this->version = $version;

        return $this;
    }
}

usage:

use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;
use Version;

$serializer = new Serializer(array(new ObjectNormalizer()));
$obj2 = $serializer->denormalize(
    array('version' => '3.0'),
    'Version',
    null
);

dump($obj2);die;

result:

Version {#795 ▼
  #version: "3.0"
}

Upvotes: 6

Related Questions