我正在使用的内容:
我正在使用JMSSerializerBundle从POST请求中反序列化JSON object
。
问题描述:
我的JSON
中的一个vaules是Id
。我想在反序列化发生之前用正确的对象替换此Id。
不幸的是,JMSSerializerBundle
没有@preDeserializer
注释。
我面临的问题(如果有@preDeserializer注释,我也会面临)是,我想为我的所有实体创建一个泛型函数。
问题:
如何以最通用的方式将我的Id
替换为相应的object
?
你也可以像我一样(使用条令)自己补水:
解决方案
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;
}