如何在 Symfony 中反序列化数组


How deserialize array in Symfony

>我想在Symfony中将数组反序列化为类,但是如果不使用例如json或XML,我找不到一种方法来做到这一点。

这是类:

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

我想反序列化为产品类的数组。

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

您需要直接使用非规范化程序。

版本:

class Version
{
    /**
     * Version string.
     *
     * @var string
     */
    protected $version = '0.1.0';
    public function setVersion($version)
    {
        $this->version = $version;
        return $this;
    }
}

用法:

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;

结果:

Version {#795 ▼
  #version: "3.0"
}
你可以

通过这样的反思来做到这一点。

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;
}

然后你会这样称呼..

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