Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clean Architecture - Where does mapping of DTO to business model should happen?

I have a DTO that's managed by a Repository and in the end I want to map this DTO to a different type of object that's used by the Presentation layer.

Should the mapping happen in the Repository or in the domain layer? ( Use case/ Interactor)

like image 449
Nameless Avatar asked Jun 18 '18 13:06

Nameless


2 Answers

In clean architecture the repository returns entities which are "used" bei the Interactors to implement the business rules. The Interactors return "response models" (DTOs) which are used by the presenters to generate "view models" which are used by the views to show results to the users.

Depending on the responsibility of ur "different type of object" the mapping would be in the Interactor or presenter.

U can find more details about Interactors and presenters in my blog post here: https://plainionist.github.io/Implementing-Clean-Architecture-Controller-Presenter/

like image 136
plainionist Avatar answered Sep 20 '22 19:09

plainionist


I think the term DTO is a little too vague to answer this question. It really depends on what the purpose of the transformation is.

For example, let's assume we have some kind of system that has a Book object in its entities (in the domain layer). The book object returned by the repositories may have a field named pendingDelete because we delete books in a background task in batches. This field is needed by the domain layer but not externally and so, in the use case layer, we transform the book object into another object (maybe by casting to an interface or maybe creating a whole new object) that does not have this field. This meets the definition of a DTO in my brain and this mapping would happen in the domain layer.

Alternatively, lets now consider that we need to transform that object into a different object that has been decorated with various annotations/metadata that instruct how to serialize the object into XML or JSON. This also meets the definition of a DTO but this mapping would happen outside of the domain layer.

In the first example, we are using the DTO to control the interface to our inner layers and so we do that mapping in the inner layers. In the second example we are using the DTO to control the interface to our outer layers and so we do that mapping in the outer layers.

like image 28
Pace Avatar answered Sep 22 '22 19:09

Pace