4

I'm on a project currently using JMS Serializer in an API. We use a lot of virtual properties - especially expression Prop in the serialization mapping.

App\Entity\MyEntity:
exclusion_policy: none
properties:
    id:
        expose: true
        groups: ['default']
virtual_properties:
    child:
        exp: object.getChildObject().getIdentifier()
        serialized_name: child_identifier
        type: string
        groups: ['default']
    amount:
        exp: object.getOtherChild().getAmount()
        serialized_name: other_child_amount
        type: string
        groups: ['default']

This would allow me to have child properties without having to create getters just for that for a more concise JSON - very useful for case where there are some logic in those virtual prop ( ex: the 'amount' in the following example )

{
    "id": 123,
    "child": "Identifier_52",
    "amount": 100
}
// instead of
{
     "id": 123,
     "child": { "identifier" : "Identifier_52" }
     "amount": { "weight": 20, "number": 5 } 
 } 

We recently thought about switching to Symfony Serializer and so far I have not found an easy way to reuse or re-implement these config (the expressions ).
Other part of the config (virtual properties that are not expression and normal properties) are reusable if I change the properties config key to attributes but not the Exp ones.

They're quite nice since I don't have to implements getters just for serialization or a custom normalizer (and pretty readable).

Is there an equivalent ?
If not what would be the closest way - to keep it as short/readable as possible and reusable accross multiple entities.

I thought about maybe creating a custom normalizer which would read an annotation/custom config on the serialization config file. I'd just need to implement it, add it to the serializer and add the config/annotation.
Is that possible ?

R.Damasinoro
  • 381
  • 2
  • 20

0 Answers0