skip to Main Content

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?

  1. Importing the model and using it directly eg.:

    User::all()

  2. Injecting it in the constructor of the service and using it like this:

    $this->userModel->all()

2

Answers


  1. 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.

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search