使用 JMSSerializer 序列化特征



尝试序列化使用特征的模型时,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

MyProjectComponentCoreModelTraitsIdentityTrait:
    exclusion_policy: NONE
    properties:
    id:
        expose: true

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

 MyProjectComponentCoreModelOurClass:
     exclusion_policy: NONE
     properties:
         test:
             expose: true

一些代码已被忽略以专注于问题

PHP

特性是从 PHP 5.4.0 开始引入的,最新的 JMSSerializer 代码支持 PHP 5.3.2。注意 "require": {"php": ">=5.3.2", 环顾代码,此功能尚不受支持。这个问题与JMSSerializer github上的这个问题非常相关。

可以使用 Trait 进行序列化:

<?php
namespace AppBundleEntity;
use JMSSerializerAnnotationExpose;
use JMSSerializerAnnotationGroups;
use JMSSerializerAnnotationType;

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

    /**
     * @ORMPrePersist()
     *
     * Set createdAt.
     */
    public function setCreatedAt()
    {
        $this->createdAt = new DateTime();
    }
    /**
     * Get createdAt.
     *
     * @return DateTime
     */
    public function getCreatedAt()
    {
        return $this->createdAt;
    }
    /**
     * @ORMPreUpdate()
     *
     * Set updatedAt.
     *
     * @return Campaign
     */
    public function setUpdatedAt()
    {
        $this->updatedAt = new DateTime();
    }
    /**
     * Get updatedAt.
     *
     * @return DateTime
     */
    public function getUpdatedAt()
    {
        return $this->updatedAt;
    }
}

不要忘记在字段上添加@type。

最新更新