0

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";
...
3

2 Answers 2

6

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"
}
Sign up to request clarification or add additional context in comments.

Comments

1

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'));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.