We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Validate and translate JSON to complex objects using Annotations?

Hello everyone!

With a couple colleagues, we're trying to validate long JSON structures and to convert them using a solution that would be easy enough using Phalcon's Annotations.

Let's say we get some data like the following as an input: {"legs": ["lower-left", "lower-right"], "arms": ["upper-left"], "name": "The one armed man" } We would then have as an output some objects that would be instances of these classes : Person(name, legs[], arms[]), Leg(position) and Arm(position).

Is it possible to use/extend/implement the existing model manager/annotations adapters to validate that said structure is valid on a set of classes? If yes, how could we use our set of "expected" classes?

Thanks a lot!

~Sjeannin



579
Accepted
answer

I finally implemented a working solution that uses the Validation and Annotations engines of Phalcon.

It works very well; the idea is to validate and build the object at the same time, so the objects' validate functions pass the Validator as a parameter, also they cascade-call each object's fields validation function, returning a valid object to their parent.

When trying to generalize the validation process in a single class, I noted that due to PHP's limitations in terms of casting, the annotations defining each class' fields types, names and "reflection in the JSON" have to be passed as parameters to the parent class.

Any feedback on the abstract I describe here is appreciated!