I started refactoring a Laravel app that has most of its logic in controllers, into services. I do not plan on using the repository pattern.
When using a model in a service class which is the better way?
-
Importing the model and using it directly eg.:
User::all()
-
Injecting it in the constructor of the service and using it like this:
$this->userModel->all()
Since you are not going to use repository
, then use it directly via import.
As I understand it, services
is used to handle business logic and repository
is used to handle model data. In less complex systems, you can use services
directly, and then when you need model data, new the corresponding model. It’s that simple.
Both methods are valid, but in many cases, injecting the model provides a good balance of flexibility and maintainability, especially as your application grows.
Ultimately, the choice depends on your specific needs and the complexity of your application. If you’re unsure, dependency injection can offer more long-term benefits.
You can use any of the stated options since you mentioned this
I do not plan on using the repository pattern.
But even if you were to use repository patterns it is not recommened to
Injecting it in the constructor of the service and using it like this:
Because it violates the D
(i.e Dependency Inversion Principle
) of SOLID
principal which state that ….
High-level modules should not depend on low-level modules, but rather both should depend on abstractions.
And to achieve abstraction you need to create a interface
that will implemented by a Solid-class
which will implement the bussiness logic. And then you can inject that solid-class
to the constructor of the Service-class
.
In this way the two module gets loosely coupled as well as it also maintain SOLID
principles.
In a large-scale system & complex project you should maintain this approach no matter which framework/language you use.