我尝试在反序列化期间使用JMS Serializer从数据库(Symfony,Doctrine)加载对象。让我们说我有一个简单的足球api应用程序,两个实体Team和Game,id为45和46的团队已经在db中。
从json创建新游戏时:
{
"teamHost": 45,
"teamGues": 46,
"scoreHost": 54,
"scoreGuest": 42,
}
游戏实体:
class Game {
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\ManyToOne(targetEntity="App\Entity\Team")
* @ORM\JoinColumn(nullable=false)
*/
private $teamHost;
/**
* @ORM\ManyToOne(targetEntity="App\Entity\Team")
* @ORM\JoinColumn(nullable=false)
*/
private $teamGuest;
我想创建一个已经从数据库加载团队的Game对象。
$game = $this->serializer->deserialize($requestBody, \App\Entity\Game::class, 'json');
寻找解决方案我发现像jms_serializer.doctrine_object_constructor
,但文档中没有具体的例子。您是否能够帮助我在反序列化期间从数据库中创建对象?
您需要创建一个自定义处理程序:https://jmsyst.com/libs/serializer/master/handlers
一个简单的例子:
<?php
namespace App\Serializer\Handler;
use App\Entity\Team;
use Doctrine\ORM\EntityManagerInterface;
use JMS\Serializer\Context;
use JMS\Serializer\GraphNavigator;
use JMS\Serializer\Handler\SubscribingHandlerInterface;
use JMS\Serializer\JsonDeserializationVisitor;
class TeamHandler implements SubscribingHandlerInterface
{
private $em;
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
public static function getSubscribingMethods()
{
return [
[
'direction' => GraphNavigator::DIRECTION_DESERIALIZATION,
'format' => 'json',
'type' => Team::class,
'method' => 'deserializeTeam',
],
];
}
public function deserializeTeam(JsonDeserializationVisitor $visitor, $id, array $type, Context $context)
{
return $this->em->getRepository(Team::class)->find($id);
}
}
虽然我建议使用通用方法来处理单个处理程序所需的实体。
示例:https://gist.github.com/Glifery/f035e698b5e3a99f11b5
此外,此问题之前已被问过:JMSSerializer deserialize entity by id