【问题标题】:Can symfony serializer deserialize return nested entity of type child entity?symfony 序列化程序可以反序列化返回子实体类型的嵌套实体吗?
【发布时间】:2015-11-07 02:09:44
【问题描述】:

当我反序列化我的学说实体时,初始对象被正确构造/启动,但是所有子关系都试图被称为数组。

正在调用根级对象的 addChild(ChildEntity $entity) 方法,但 Symfony 抛出错误,表明 addChild 正在接收数组而不是 ChildEntity 的实例。

Symfony 自己的序列化器是否有办法将嵌套数组(子实体)反序列化为实体类型?

JMS 序列化程序通过在属性上指定 @Type("ArrayCollection<ChildEntity>") 注释来处理此问题。

【问题讨论】:

  • 嘿,找到方法了吗?

标签: php symfony serialization doctrine-orm


【解决方案1】:

我相信 Symfony 序列化器与 JMS 序列化器相比尝试最小化,因此您可能必须为该类实现自己的非规范化器。你可以看看the section on adding normalizers.

【讨论】:

    【解决方案2】:

    可能有一种更简单的方法,但到目前为止,对于 Symfony,我正在使用鉴别器接口注释和对象数组的类型属性。它还可以在一个数组中处理多种类型(MongoDB):

    namespace App\Model;
    
    use Symfony\Component\Serializer\Annotation\DiscriminatorMap;
    
    /**
     * @DiscriminatorMap(typeProperty="type", mapping={
     *    "text"="App\Model\BlogContentTextModel",
     *    "code"="App\Model\BlogContentCodeModel"
     * })
     */
    interface BlogContentInterface
    {
        /**
         * @return string
         */
        public function getType(): string;
    }
    

    父对象需要将属性定义为接口并获取、添加、删除方法:

        /**
         * @var BlogContentInterface[]
         */
        protected $contents = [];
        
        /**
         * @return BlogContentInterface[]
         */
        public function getContents(): array
        {
            return $this->contents;
        }
    
        /**
         * @param BlogContentInterface[] $contents
         */
        public function setContents($contents): void
        {
            $this->contents = $contents;
        }
    
        /**
         * @param BlogContentInterface $content
         */
        public function addContent(BlogContentInterface $content): void
        {
            $this->contents[] = $content;
        }
    
        /**
         * @param BlogContentInterface $content
         */
        public function removeContent(BlogContentInterface $content): void
        {
            $index = array_search($content, $this->contents);
            if ($index !== false) {
                unset($this->contents[$index]);
            }
        }
    

    【讨论】:

      猜你喜欢
      • 2019-08-01
      • 2019-07-07
      • 2018-09-19
      • 2021-09-27
      • 1970-01-01
      • 2019-04-10
      • 1970-01-01
      • 1970-01-01
      • 2016-10-11
      相关资源
      最近更新 更多