使用Doctrine和JMSSerializer注释序列化对象数组

时间:2016-11-02 13:43:38

标签: php symfony doctrine-orm fosrestbundle jms-serializer

我有一个模特

    /**
     * @ORM\Table(name="polygon")
     * @ORM\Entity(repositoryClass="MyBundle\Repository\PolygonRepository")
     * @JMS\ExclusionPolicy("none")
     */
    class Polygon {
         /**
          * @var string
          *
          * @ORM\Column(name="polygon", type="json_array")
          * @JMS\Type("array<MyBundle\Model\Point>")
          */
          private $points;

          /***/
    }

在数据库中,它存储为文本'[{“x”:1,“y”:1} ...]'

在控制器中我有

/**
 * Matches /polygon exactly
 *
 * @Route("/", name="polygon_list")
 * @Method("GET")
 *
 * @Rest\Get("/")
 *
 */
public function listAction()
{
    return $this->container->get('doctrine.orm.entity_manager')
        ->getRepository('MyBundle:Polygon')
        ->findAll();
}

所以我得到了 ReflectionProperty :: getValue()期望参数1是对象,给定数组

in ... vendor / jms / metadata / src / Metadata / PropertyMetadata.php:51

如果只是为了获得结果,可以通过使用虚拟属性

来解决
/**
 * @JMS\Exclude
 */
private $points;

/**
 * @JMS\VirtualProperty
 * @JMS\Type("array<MyBundle\Model\Point>")
 * @JMS\SerializedName("points")
 * @JMS\Groups({"common"})
 *
 * @return array
 */
public function getMyPoints() {
    return [new Point(), new Point()]
}

但是我需要从POST接收这些点作为JSON,所以到目前为止我找到的唯一方法是Doctrine自定义类型类似于 https://github.com/sonata-project/sonata-doctrine-extensions

唯一的区别是在convertToPHPValue方法中我添加了额外的类型转换来接收对象而不是关联数组:

// pass my [{"x":1, "y":1} ...]
public function convertToPHPValue($value, AbstractPlatform $platform)
    {
       return array_map(function($a){ return (object)$a;}, json_decode($value));
    }

是否有更干净的解决方案,而不添加自定义Doctrine序列化?

如果只是这个 ...供应商/ JMS /元/ src目录/元/ PropertyMetadata.php:51

return $this->reflection->getValue((object)$obj);

但是

return $this->reflection->getValue($obj); // :(

1 个答案:

答案 0 :(得分:0)

我的问题在于使用@JMS \ Type

    class Polygon {
         /**
          * @ORM\Column(name="polygon", type="json_array")
          */
          private $points;

          public function getPoints() { return $this->points;}
          public function setPoints($points) {
               $this->points = $points;
               return $this;
          }
          /***/
    }

工作得很好,感谢@Matteo指出我让事情复杂化了。)