使用JMSSerializer序列化特征

时间:2014-11-14 17:59:20

标签: php symfony jmsserializerbundle jms-serializer

尝试序列化使用特征的模型时,JMSSerializer不会序列化该特征所包含的属性。我正在使用yaml来配置序列化程序,但它似乎无法正常工作。

trait IdentityTrait
{

    protected $id;

    public function setId($id)
    {
        $this->id = $id;

        return $this;
    }

    public function getId()
    {
        return $this->id;
    }
}

class OurClass {
   use IdentityTrait;

   protected $test;

   public function getTest() {
       $this->test;
   }
}

使用JMSSerializerBundle,以下yaml位于Resources/config/serializer/Model.Traits.IdentityTrait.yml

MyProject\Component\Core\Model\Traits\IdentityTrait:
    exclusion_policy: NONE
    properties:
    id:
        expose: true

OurClass配置位于Resources/config/serializer/Model.OurClass.yml

 MyProject\Component\Core\Model\OurClass:
     exclusion_policy: NONE
     properties:
         test:
             expose: true

某些代码已被忽略以关注问题

2 个答案:

答案 0 :(得分:1)

PHP 5.4.0以来引入了PHP特征,最新的JMSSerializer代码支持PHP 5.3.2。注意"require": {"php": ">=5.3.2",查看代码,(尚未)支持此功能。此问题与JMSSerializer github上的this issue非常相关。

答案 1 :(得分:0)

可以使用Trait进行序列化:

<?php
namespace AppBundle\Entity;

use JMS\Serializer\Annotation\Expose;
use JMS\Serializer\Annotation\Groups;
use JMS\Serializer\Annotation\Type;


trait EntityDateTrait
{
    /**
     * @var \DateTime
     *
     * @ORM\Column(name="created_at", type="datetime", nullable=true)
     * @Expose()
     * @Groups({"DeploymentListing", "DeploymentDetails"})
     * @Type("DateTime")
     */
    protected $createdAt;

    /**
     *
     * @var \DateTime
     *
     * @ORM\Column(name="updated_at", type="datetime", nullable=true)
     * @Expose()
     * @Groups({"DeploymentListing", "DeploymentDetails"})
     * @Type("DateTime")
     */
    protected $updatedAt;


    /**
     * @ORM\PrePersist()
     *
     * Set createdAt.
     */
    public function setCreatedAt()
    {
        $this->createdAt = new \DateTime();
    }

    /**
     * Get createdAt.
     *
     * @return \DateTime
     */
    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    /**
     * @ORM\PreUpdate()
     *
     * Set updatedAt.
     *
     * @return Campaign
     */
    public function setUpdatedAt()
    {
        $this->updatedAt = new \DateTime();
    }

    /**
     * Get updatedAt.
     *
     * @return \DateTime
     */
    public function getUpdatedAt()
    {
        return $this->updatedAt;
    }
}

别忘了在字段上添加@type。

相关问题