如何在Symfony

时间:2016-02-19 09:53:57

标签: php arrays json symfony deserialization

我想在Symfony中将数组反序列化为类,但是如果不使用例如json或XML,我就无法找到方法。

这是课程:

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

} 

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

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

2 个答案:

答案 0 :(得分:3)

您需要直接使用denormalizer。

版本:

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

答案 1 :(得分:2)

你可以通过像这样的反射来做到这一点..

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