3

I'd like to have two different representations for the same entity using the PHP library JMSSerializer, which can easily be achieved by its groups feature.

The problem is that I have one representation where the properties of a sub object are inlined, and once they are not. It would be nice if it works somehow like this:

<?xml version="1.0" encoding="UTF-8"?>
<serializer>
    <class name="SomeEntity">
        <property name="structure" type="SomeOtherEntity" groups="group1" inline="true"/>
        <property name="structure" type="SomeOtherEntity" groups="group2"/>
    </class>
</serializer>

What I wanted to accomplish this way, was that SomeEntity could be serialized using group1 with SomeOtherEntity being inlined, and with group2 if SomeOtherEntity should not be inlined, but that doesn't seem to work (I guess the name attribute is kind of unique).

A solution would be to introduce another method in combination with a VirtualProperty, but then I would have to touch the class, which I would prefer to avoid, since it is a pure serialization issue.

Any better ideas how to solve this?

Daniel Rotter
  • 1,998
  • 2
  • 16
  • 33
  • Basically for legacy reasons. The idea is not to have both of them, but only one of both definitions, based on which serialization groups are passed when serializing the object. I need a representation where the object is contained in its own property, and one in which it doesn't (that's what inline is doing). – Daniel Rotter Jan 26 '16 at 14:29
  • Sorry, I deleted my comment after I realized your question had a good point. ;) – Genti Saliu Jan 26 '16 at 14:31
  • Isn't this something a handler can do? http://jmsyst.com/libs/serializer/master/handlers I will write an answer based on this. – Genti Saliu Jan 26 '16 at 14:34
  • Hm, you are right, with some additional logic this might be possible... Probably the way to go, although I leave the question open, in case there is somebody having a better solution :-) – Daniel Rotter Jan 26 '16 at 14:36
  • And what I don't like about handlers is that they are always bound to a certain format :-/ It's also a bit annoying that you can't use `addData` on the visitor, if it is serialized using XML. – Daniel Rotter Jan 26 '16 at 14:42
  • As you say about the virtualProperties it can be a solution, but you don't need to touch the class, you can basically make 2 virtual properties one with inline and other without it, and put them in different groups, and the original property you can make it expose false. – Renato Mefi Jan 26 '16 at 14:58
  • But the virtual property needs a method, which it calls. If this method does not exist yet, the class has to be touched, or am I missing something? – Daniel Rotter Jan 26 '16 at 15:02
  • Inherit the class and add the method in the child class. This way you avoid touching the parent class. It's also the quickest solution. – Genti Saliu Feb 05 '16 at 15:03

0 Answers0