Why shouldn't the repository return a DTO?

Everywhere they write that the repository should not return a DTO... What should I do then? return an object or an array? But you can add anything to it, anywhere. If I change the received data, the repository will give it immediately along with them, and I won't even notice it. DTO, in fact, guarantees that I will receive the object in a single form, and in the future I can see what I accept and what I give.

I use the repository purely for CRUD actions to have a layer for eloquent models, if I decide to replace them.

Tell me, what is better to do in my case?

Author: Paul Wall, 2020-04-14

1 answers

DTO is a Data Transfer Object. That is, an object that is used to transfer data to the client or vice versa to receive data from it.

The format of transmitting this data may well not correspond to the database structure, and most often it should not correspond to it. If you transfer the data in its pure form, as they are presented in the tables/models of the database, it is not always convenient for the client to work as a result of the complex structure, the presence of unnecessary (which this client does not have within this task). processes) data, an inappropriate representation of the data (for example, you need to convert the format of the date, time, etc.).

In addition, the use of DTO as a model for the repository leads to strong connectivity in the code due to violations of the MVC principle, and as a natural result, the support and development of such code becomes noticeably more complicated, and sometimes becomes simply impossible. For example, if your service has 2 clients, each of which requires approximately the same data, but in different views and / or with minor differences. You won't have your own table structure with the same data for each of them, will you?..

Yes, and if your protocol is the same for all clients. Over time, there may be a task to change something. What is easier to change, the structure of the tables or a simple algorithm for converting the model to DTO?

Therefore, it is better to separate the DTO and the models. And the repository really shouldn't work with the DTO. I'll say more. The logic of working with DTO in ideally, it should not go beyond the "transport" layer (in MVC, these are controllers).

 3
Author: Streletz, 2020-04-14 13:29:41