Serializing traits with JMSSerializer

2.6k views Asked by At

When trying to serialize a model that uses traits, JMSSerializer does not serialize properties included by that trait. I am using yaml to configure the serializer but it seems that it's not working.

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 is used and the following yaml is located in Resources/config/serializer/Model.Traits.IdentityTrait.yml

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

And the OurClass configuration is located in Resources/config/serializer/Model.OurClass.yml

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

Some code has been ignored to focus on the problem

2

There are 2 answers

0
ilyes kooli On

PHP traits are introduced since PHP 5.4.0, the latest JMSSerializer code supports PHP 5.3.2. Note "require": {"php": ">=5.3.2", Looking around the code, this feature is not supported (yet). This problem is very related to this issue on JMSSerializer github.

0
Yohann Daniel Carter On

It's possible to Serialize with 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;
    }
}

Don't forget to add @type on fields.