【问题标题】:Construct object during deserialization on JMS Serializer在 JMS Serializer 上反序列化期间构造对象
【发布时间】:2023-04-02 17:53:01
【问题描述】:

我尝试在使用 JMS 序列化器进行反序列化期间从数据库(Symfony、Doctrine)加载对象。假设我有一个简单的足球 api 应用程序,两个实体 TeamGame,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 的内容,但文档中没有具体示例。 您能帮我在反序列化期间从数据库中创建一个对象吗?

【问题讨论】:

    标签: symfony serialization deserialization jms-serializer


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-20
      • 1970-01-01
      • 1970-01-01
      • 2017-12-02
      • 2015-08-03
      相关资源
      最近更新 更多