JMSSerializer - Custom handler for a property

93 Views Asked by At

I know that I can declare a custom handler for a whole type. But what if I want to use different approach for serializing the same type in different situation?

For example I have an entity, it has a property int $popularity. But I want serializer to process it first (for example multiply it by 2).

Classes:

class Foo {
    public int $popularity = 10;
}

class PopularityProcessor() {
    public function process (int $popularity) { return $popularity * 2; }
}

Mapping:

App\Entity\Foo:
    properties:
        popularity: ~

Here, when serializing to json, I don't want the serializer to just use $foo->popularity to get the value of the property. Instead, I want it to do something with the value and then return, e.g.

return $this->popularityProcessor->process($foo->popularity);

Since $popularity is an integer, I can not register a custom handler for it. What can be the solution?

1

There are 1 best solutions below

2
On

You could use Virtual Properties for this case. This means you add a method in the Foo class which calls to the processor or do the logic directly in the method.

Example:

class Foo {
  public int $popularity = 10;

 /**
  * @Serializer\VirtualProperty()
  */
  public function processPopularity(): int
  {
    return $this->popularity * 2;
  }
}

You could use the Serialized Name to make it available as "popularity" and exclude the property from serializing. You can find information about it there: https://jmsyst.com/libs/serializer/master/reference/annotations#virtualproperty