在JMS序列化器中反序列化时构造对象

3

我尝试使用JMS序列化器从数据库(Symfony,Doctrine)加载对象进行反序列化。假设我有一个简单的足球API应用程序,两个实体TeamGame,在数据库中已经有ID为45和46的团队。

当从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 = $this->serializer->deserialize($requestBody, \App\Entity\Game::class, 'json');

我发现类似于jms_serializer.doctrine_object_constructor的解决方案,但文档中没有具体的示例。您能否帮助我在反序列化过程中从数据库创建对象?
1个回答

4
您需要创建一个自定义处理程序: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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接