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()
2
Answers
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.
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 andrepository
is used to handle model data. In less complex systems, you can useservices
directly, and then when you need model data, new the corresponding model. It’s that simple.