为什么除了json中的数据之外的所有值都用null实例化新实体,为什么实体构造函数不设置默认值-在构造函数中放置die()永远不会执行。
更新:
深入代码,当没有找到托管实体时,JMSS将使用原则实例化器类来创建实体——它的唯一工作是创建实体而不调用构造函数。这有什么原因吗?这是在JMSSerializerConstructionUnserializeObjectConstructor
我已经将对象构造函数配置为使用JMS编写的原则对象构造函数,但无论是否使用该构造函数,都会发生相同的问题。
jms_serializer.object_constructor:
alias: jms_serializer.doctrine_object_constructor
public: false
已存在的实体可以轻松更新,但是新实体缺少所有构造函数设置默认值。
在'fields'下,元素0是已经存在的,元素1是新的。
array (size=3)
'id' => int 2
'name' => string 'Categories' (length=10)
'fields' =>
array (size=2)
0 =>
array (size=7)
'id' => int 49
'displayName' => string 'Car Branded' (length=11)
'type' => string 'checkboxlist' (length=12)
'required' => boolean false
'disabled' => boolean false
'name' => string 'h49' (length=3)
1 =>
array (size=3)
'type' => string 'email' (length=5)
'name' => string 'field3491' (length=9)
'displayName' => string 'Email' (length=5)
反序列化后的实体是这样的:
object(stdClass)[2000]
public '__CLASS__' => string 'AppBundleEntityFormElement' (length=28)
public 'id' => null
public 'label' => string 'Email' (length=5)
public 'type' => string 'email' (length=5)
public 'defaultValue' => null
public 'required' => null
public 'mappedField' => null
public 'garbageCollection' => null
public 'sortOrder' => null
public 'disabled' => null
public 'uuid' => null
public 'form' => null
public 'multiOptions' => null
public 'filters' => null
public 'submissions' => null
实体构造函数:
public function __construct()
{
$this->required = false;
$this->disabled = false;
$this->garbageCollection = false;
$this->sortOrder = 0;
$this->type = 'text';
}
最后我是这样反序列化的:
$serializer = $this->get('jms_serializer');
$entryForm = $serializer->deserialize($json_data, 'AppBundleEntityEntryForm', 'json');
问题是默认的ObjectConstructor使用Doctrine的Instantiator,它不调用类的构造函数。要解决这个问题,您可以创建自己的ObjectConstructor,它只返回类的一个新实例。
的例子:
<?php
namespace AppBundleSerializer;
use JMSSerializerConstructionObjectConstructorInterface;
use JMSSerializerDeserializationContext;
use JMSSerializerMetadataClassMetadata;
use JMSSerializerVisitorInterface;
class ObjectConstructor implements ObjectConstructorInterface
{
/**
* {@inheritdoc}
*/
public function construct(
VisitorInterface $visitor,
ClassMetadata $metadata,
$data,
array $type,
DeserializationContext $context
) {
$className = $metadata->name;
return new $className();
}
}
如果您正在使用bundle,只需将jms_serializer.unserialize_object_constructor.class
参数设置为新类。否则,在您的构建器中,使用类作为您的对象构造函数。
对我来说有效的是简单地将此添加到jms_serializer配置中:
jms_serializer:
object_constructors:
doctrine:
fallback_strategy: "fallback"