【问题标题】:Generic Deserializing : JSON ID value to Object通用反序列化:对象的 JSON ID 值
【发布时间】:2016-01-28 13:53:15
【问题描述】:
我正在使用什么:
我正在使用 JMSSerializerBundle 从 POST 请求中反序列化我的 JSON object。
问题描述:
我的JSON 中的一个值是Id。我想在反序列化发生之前用正确的对象替换这个 Id。
很遗憾,JMSSerializerBundle 没有 @preDeserializer 注释。
我面临的问题(如果有 @preDeserializer 注释我会面临)是我想为我的所有实体创建一个通用函数。
问题:
如何以最通用的方式将我的Id 替换为对应的object?
【问题讨论】:
标签:
php
json
symfony
jmsserializerbundle
【解决方案1】:
您也像我一样(使用 Doctrine)进行自己的补水:
解决方案
IHydratingEntity 是我所有实体都实现的接口。
hydrate 函数一般在我的 BaseService 中使用。参数是实体和json对象。
在每次迭代中,该函数将测试该方法是否存在,然后它将调用reflection 函数来检查参数的方法(setter)是否也实现了IHydratingEntity。
如果是这种情况,我使用 id 通过 Doctrine ORM 从数据库中获取实体。
我认为可以优化这个过程,所以请务必分享您的想法!
protected function hydrate(IHydratingEntity $entity, array $infos)
{
#->Verification
if (!$entity) exit;
#->Processing
foreach ($infos as $clef => $donnee)
{
$methode = 'set'.ucfirst($clef);
if (method_exists($entity, $methode))
{
$donnee = $this->reflection($entity, $methode, $donnee);
$entity->$methode($donnee);
}
}
}
public function reflection(IHydratingEntity $entity, $method, $donnee)
{
#->Variable declaration
$reflectionClass = new \ReflectionClass($entity);
#->Verification
$idData = intval($donnee);
#->Processing
foreach($reflectionClass->getMethod($method)->getParameters() as $param)
{
if ($param->getClass() != null)
{
if ($param->getClass()->implementsInterface(IEntity::class))
#->Return
return $this->getDoctrine()->getRepository($param->getClass()->name)->find($idData);
}
}
#->Return
return $donnee;
}