Answer the question
In order to leave comments, you need to log in
How to properly use services and repositories in a web application?
I use yii and laravel frameworks. I always had all the logic in the models. I heard about the use of services, repositories to process all the logic. But why are they needed and how to use them I do not know. Please explain or give links to good articles/videos. Thank you.
Answer the question
In order to leave comments, you need to log in
Yii2 and Laravel use Active Record instead of Entity and Repository, i.e. data description and access to it.
Service is a layer in which business logic is executed in Java, although .Net often directly in models. (The first is called anemic models, some see it as the right architecture, some as an anti-pattern).
This is me to the fact that in architecture there is more philosophy than engineering.
In general, do not bother. If you just have CRUD, then it makes no sense to produce a bunch of abstractions and you need to use Active Record and requests through it in the controller.
If queries are more complicated and this is already related to the domain area, then we write in Active Query in Yii2 and methods for each situation, so that when replacing logic, we don’t have to search through the entire code. But this is the case if it is the application, and not a specific action.
If there is some simple logic, such as adding two numbers, then you can directly in Active Record itself, if something is already more complicated, then it can be taken out to the Service level about which you asked. Then it will query the Active Record, and the Controller will work with the Service.
Repository provides an abstraction over the repository, but I wouldn't use it with Yii2. It’s also a very ambiguous thing, what in Java for some reason is called a Repository, in fact, is just a DAO, while in .Net they use real Repositories.
The main rule, if there is a lot of code and you start to get lost in it, you need to think about how to separate it. The rest is with experience!
In the lara, use Eloquent - this is the very repository. Some manage to create a repository for a repository. IMHO, crap.
And keep all logic in services. Simply put, services are just a regular class found in the app/Services folder. Do not forget to assign a namespace to him only to address by name.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question