JMSSerializerBundle与抽象类 - Symfony2

时间:2016-04-20 09:09:59

标签: php symfony jmsserializerbundle jms-serializer

我想序列化和反序列化具有依赖性的实体,但我无法序列化与抽象类有关的元素。

层次结构:

测试 - >几个Calls其中Call类是一个抽象类,并由TestCallExecuteQuery扩展(与$conditions相同的问题)

Test.php:

/**
 * @ORM\Entity(repositoryClass="Gedmo\Sortable\Entity\Repository\SortableRepository")
 * @ORM\Table(name="cfa_test")
 * @JMSSer\ExclusionPolicy("all")
 */
class Test
{

    /**
     * @ORM\OneToMany(targetEntity="TestCall", mappedBy="test", cascade={"all"}, orphanRemoval=true)
     * @JMSSer\Expose
     * @JMSSer\Groups({"export"})
     * @JMSSer\Type("ArrayCollection<App\Bundle\CapFileAnalyzerBundle\Entity\TestCall>")
     */
    protected $calls;

    /**
     * @ORM\OneToMany(targetEntity="TestCondition", mappedBy="test", cascade={"all"}, orphanRemoval=true)
     * @JMSSer\Expose
     * @JMSSer\Groups({"export"})
     * @JMSSer\Type("ArrayCollection<App\Bundle\CapFileAnalyzerBundle\Entity\TestCondition>")
     */
    protected $conditions;

TestCall.php:

/**
 * @ORM\Entity
 * @ORM\InheritanceType("SINGLE_TABLE")
 * @ORM\Table(name="cfa_test_call")
 * @ORM\DiscriminatorColumn(name="type", type="string")
 * @ORM\DiscriminatorMap({
 *      "executeQuery" = "App\Bundle\CapFileAnalyzerBundle\Entity\TestCallExecuteQuery",
 *      "call" = "App\Bundle\CapFileAnalyzerBundle\Entity\TestCall"
 * })
 * @JMSSer\ExclusionPolicy("all")
 * @JMSSer\Discriminator(field="serializedType", map={
 *      "executeQuery"="App\Bundle\CapFileAnalyzerBundle\Entity\TestCallExecuteQuery",
 *      "call" = "App\Bundle\CapFileAnalyzerBundle\Entity\TestCall"
 * })
 */
abstract class TestCall
{
    /**
     * @JMSSer\Expose
     * @JMSSer\Groups({"export"})
     */
    protected $type = 'call';

    /**
     * @ORM\Id
     * @ORM\Column(name="id", type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\ManyToOne(targetEntity="Test", inversedBy="calls")
     */
    protected $test;
  /**
     * @JMSSer\VirtualProperty()
     * @JMSSer\SerializedName("serializedType")
     */
    public function getDiscr()
    {
        return $this->type;
    }

TestCallExecuteQuery.php:

/**
 * @ORM\Entity
 * @JMSSer\ExclusionPolicy("all")
 */
class TestCallExecuteQuery extends TestCall
{

    protected $type = 'executeQuery';

    /**
     * @ORM\Column(name="`query`", type="text")
     * @JMSSer\Expose
     * @JMSSer\Groups({"export"})
     */
    protected $query;

    /**
     * @ORM\Column(name="`return`", type="string", nullable=true)
     * @JMSSer\Expose
     * @JMSSer\Groups({"export"})
     */
    protected $return;

所以我按照互联网上的说明进行操作:

  • @JMSSer\Expose注释,每个班级都有@JMSSer\ExclusionPolicy("all")
  • 在抽象类@JMSSer\Discriminator之上的
  • TestCall注释与extender类(TestcallExecuteQuery)进行映​​射

但..当我序列化时,我只获得TestCall的type属性,但query中没有定义returnTestCallExecuteQuery属性:

{"tests":[{"calls":[{"type":"executeQuery"},{"type":"executeQuery"}], ... }

我知道这是可能的,因为我把它们拿到了,但即使把时钟倒转,我也无法再现它。

{"tests":[{"calls":[{"query":"SELECT * FROM table","return":"return_1"}], ... }

编辑:

好的,我可能通过更改query来获得returnTest.php

/**
 * @JMSSer\Type("ArrayCollection<App\Bundle\CapFileAnalyzerBundle\Entity\TestCall>")
 */
    protected $calls;

致:

/**
 * @JMSSer\Type("ArrayCollection<App\Bundle\CapFileAnalyzerBundle\Entity\TestCallExecuteQuery>")
 */
    protected $calls;

我做错了什么?

1 个答案:

答案 0 :(得分:0)

好的!几天后我失去理智后找到了一个解决方案!

解决方案是创建两个事件侦听器PreSerialize和PostSerialize

首先,我在TestCall.php(抽象类)中删除了这部分:

/**
 * @JMSSer\VirtualProperty()
 * @JMSSer\SerializedName("serializedType")
 */
public function getDiscr()
{
    return $this->type;
}

并在TestCallExecuteQuery.php(扩展程序类)中添加了这些注释:

/**
 * @JMSSer\Type("string")
 * @JMSSer\Expose
 * @JMSSer\Groups({"export"})
 */
protected $type = 'executeQuery';

我的听众看起来像这样:

<?php

namespace App\Bundle\CapFileAnalyzerBundle\EventListener;

use JMS\Serializer\EventDispatcher\Events;
use JMS\Serializer\EventDispatcher\EventSubscriberInterface;
use JMS\Serializer\EventDispatcher\ObjectEvent;
use JMS\Serializer\EventDispatcher\PreSerializeEvent;

class JMSSerializerListener implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return [
            ['event' => Events::PRE_SERIALIZE, 'method' => 'onPreSerialize'],
            ['event' => Events::POST_SERIALIZE, 'method' => 'onPostSerialize']
        ];
    }

    /**
     * @param PreSerializeEvent $event
     */
    public function onPreSerialize(PreSerializeEvent $event)
    {
        $object = $event->getObject();

        if (is_object($object) &&
            is_subclass_of($object, 'App\Bundle\CapFileAnalyzerBundle\Entity\TestCall') &&
            get_class($object) !== $event->getType()['name']
        ) {
            $event->setType(get_class($event->getObject()));
        }
    }

    /**
     * @param ObjectEvent $event
     */
    public function onPostSerialize(ObjectEvent $event){
        $object = $event->getObject();
        if (is_object($object) &&
            is_a($object, 'App\Bundle\CapFileAnalyzerBundle\Entity\TestCallExecuteQuery')) {
            $event->getVisitor()->addData("serializedType", $object->getType());
        }
    }
}

听众宣言:

<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <parameters>      
        <parameter key="cfa.events.jmsserializer_listener.class">App\Bundle\CapFileAnalyzerBundle\EventListener\JMSSerializerListener</parameter>
    </parameters>

    <services>
         <service id="cfa.events.jmsserializer_listener" class="%cfa.events.jmsserializer_listener.class%">
            <tag name="jms_serializer.event_subscriber"/>
        </service>

    </services>
</container>

我解释一下:

  1. PreSerailize Event
  2. 如果要序列化的对象是我的抽象类的子类(在我的例子中是TestCall),我必须强制将事件对象的类型序列化到相关的子类中(TestCallExecuteQuery在我的情况下)。实际上,传递了正确的对象(TestCallExecuteQuery),但它与其父类(抽象类TestCall

    进行了映射

    转储$event对象:

    PreSerializeEvent {#977 ▼
      -object: TestCallExecuteQuery {#981 ▼
        #type: "executeQuery"
        #query: "SELECT * FROM table_name"
        #return: "return_3"
        #id: 2
        #test: Test {#948 ▶}
      }
      #type: array:2 [▼
        "name" => "App\Bundle\CapFileAnalyzerBundle\Entity\TestCall"
        "params" => []
      ]
      -context: SerializationContext {#420 ▶}
    }
    
    1. PostSerialze事件
    2. 如果序列化对象是我的子类,我添加访问者属性(不是虚拟甚至自定义)..

      注意:JMSSerializeBundle没有序列化&#34;虚拟&#34;属性直接添加到类中,例如通过类似的方法:

      public function createProperty($name, $value) {    
           $this->{$name} = $value;    
      }
      

      也许像JMSSerializerBundle中的那样添加了Discriminator / Virtual Property,这就是为什么它们没有被序列化。真的不知道。