Include a method when object is serialized in JMS

485 views Asked by At

I have a method that returns a value:

/**
* @ORM\Table()
* @ORM\Entity(repositoryClass="PersonRepository")
*/
class Person {

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

   public function getFoo(){
      return $this->id + 1;
   }

 //setters & getters

}

I would like to include the value that getFoo() returns when I serialize a Person object so that it would look like this:

{
   'id' : 25
   'foo' : 26
}
1

There are 1 answers

3
Jovan Perovic On BEST ANSWER

You need to set @VirtualProperty and @SerializedName.

use JMS\Serializer\Annotation\VirtualProperty;
use JMS\Serializer\Annotation\SerializedName;

class Person {
   ....
   ....
   ....

   /**
    * @VirtualProperty
    * @SerializedName("foo")
    */
   public function getFoo(){
      return $this->id + 1;
   }

    ....
    ....
    ....
}

You can read more about it here: http://jmsyst.com/libs/serializer/master/reference/annotations

Pay attention that this only works for serialization and not for deserialization.