What is the purpose of repository when service classes can do the same? What is the purpose of repository when service classes can do the same? laravel laravel

What is the purpose of repository when service classes can do the same?


From DDD (Domain Driven Design) the responsibility of a repository is to take care of loading, storing, modifying and deleting an entity on the designated data storage (which may or may not be a database -- it may even be a remote server or just a file).

A service, on the other hand, has (or should have) a very narrow responsibility of performing some useful activity. Each service is instantiated separately and then injected into code in the application layer or above, which acts as a bridge (Bridge pattern). This approach has proven to be very advantageous because it allows to manage the dependencies between otherwise unrelated (uncoupled) code.

Those two definitions and the origin of the concepts shows that they actually are very different things. By pure chance you noticed that a repository and a service have an apparent overlap, but that's due to implementation details or plain misuse. Their responsibilities may under circumstances go hand in hand (giving rise to a collaboration) but they really are orthogonal concepts.

Furthermore, Repositories should arise from a deep layer (Persistance or DAL, Data Access Layer). Services, on the other hand, often are vertical cross-cutting or arise on the application layer.

Through proper layering the differences between repositories and services become even more apparent.

Do not think about them as pure code artifacts you can move around. They are well-defined concepts useful to understand about and design the structure of a system. They decline into actual code only as a consequence of that design.

I hope I succeeded in writing something that clears up some ideas and is not confusing.


There is no definitive answer for your question since the patterns you use highly depend on the project's complexity and needs.

However, a Service and a Repository are two different things. The Repository is a common wrapper for the model and is where you write the queries to the database. IMO you shouldn't add logic here and the sole purpose of a repository is to grab os store data into the database. The advantage of Repositories is the "easiness" to switch to other database systems.

A Service, IMO, is where you add all the application's logic.

For additional information refer to this answer.


My project manager said:

use the Repository Pattern for plain PHP.

use the Service Pattern for the Laravel project.

I don't know the exact reason. but he has a lot of knowledge and experience.