Symfony Restful Post: JMSSerializerBundle vs Symfony Form Components
Asked Answered
S

2

6

As far as i understand it right JMSSerializerBundle's deserialisation does the same same as the symfony form component when a controller gets an post/put/patch request?

So either i create a symfony custom formType for e.g. an UserType and when i get a request i do something like $form->handleRequest($request) or i use JMSSerializerBundle to unserialize the request to a document/entity which gets finally stored.

Does anyone have experience with both methods? Currently i'm only familiar with the form way... Which one should i choose?

The Application i'm talking about is purely Restful, there are no twig html templates and FOSRestbundle is doing all the RESTful routing.

Stead answered 4/7, 2014 at 10:27 Comment(1)
I have exactly the same problem. Should I use Serializer Component or Form Component to handle POST/PUT? It seems Serializer is more suitable for REST?Sympathy
D
7

In our restfull API we usually use the Symfony Serializer component to handle the deserialization of entities, then the Symfony Validator component to ensure that the entities fulfill all the required conditions before pushing/updating them in database. Works pretty well, lighter than the form component.

Anyway The Form component would not be able to deserialize the json/xml so you'll have to use a serializer.

Distrain answered 4/7, 2014 at 19:46 Comment(2)
Sounds pretty feasible. When i call "$form->handleRequest($request)" is it finally JMSSerializerBundle which takes care of the deserialisation of the data in the request?Stead
this link has a good use case that explain all that you need (status code, errors serialization, ...) It does use the form component after having unserialize the entity, but as we have discussed above, you can directly use the validator component instead for simple cases.Distrain
G
1

The benefit of the Symfony\Form component over the JMS Serializer is that the validation is done before deserialization which fits into PHP 7 strict typing. Example case - you pass an array instead of a string, JMS creates and object and the getter raises a \TypeError instead of a validation error from the validator.

Gildagildas answered 16/8, 2017 at 10:14 Comment(1)
Also, handling JSON uploads for FormComponent can be done by transforming php://input into Request object. You can look up on FOSRestBundle's request handler which does this for you when enabled in Symfony framework. This has the benefit of handling PATCH requests (which original answer could not do easily) and allowing either type for requests to go through (both simple forms and JSON requests will still work).Pix

© 2022 - 2024 — McMap. All rights reserved.