Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize on Controller or Service layer?

I'm working on a REST API with Symfony2 which receives data in JSON format.

Where is the right place to convert JSON to objects:

  • Controller transforms JSON to/from object and call Service method passing a PHP object which also returns an object?
  • Controller pass the JSON to Service method and it transforms JSON to object and converts the resultant object to JSON before returning?
like image 767
acanimal Avatar asked Dec 11 '25 05:12

acanimal


1 Answers

It definitely doesn't belong to the service layer because it's supposed to work in terms of model objects. You can have lots of different UIs in an application — HTML, REST, command line — and all of them will use different formats for data exchange. Making the service layer responsible for handling all these formats doesn't make sense.

Each type of UIs has its own layer of controllers — or commands in the case of a command line UI — and it's the responsibility of those controllers to convert data to and from model objects before passing them to the service layer and back.

How exactly you do that — directly in controller actions, or delegating to other services, or using AOP — is your choice. Just keep it out of the service layer — domain layer, that is.

like image 90
Elnur Abdurrakhimov Avatar answered Dec 13 '25 19:12

Elnur Abdurrakhimov