mercredi 11 novembre 2020

laravel using `new` keyword for models in controllers

I know this might be the point of view question which has no place on SO, but I am really trying to get experienced developer's thoughts.

In my controllers, I don't want to use models directly. So I use services injected in a controller's constructor.

In the services, we have 2 ways to initialize models.

  • inject them in a service's constructor.
  • use the models directly in a service's functions, like new userModel().

Option 1 explanation: I can see the advantage of the first option, due to the fact that I can test service's functions without touching database models, since I will mock the models which gives me the option that I separately test service's functions without actually doing anything on models/databases.

Option 2 explanation: for the second option, all I can see is a disadvantage due to the fact that in order to test a service's function, I also have to know in advance what models(database) returns . These kind of tests are also necessary, but we also need to test service's functions without touching databases.

What are your thoughts on this ? I'd really appreciate it if you could give your thoughts on this even though this question mightn't deserve to be here, since getting an answer takes lots of struggles without using stackoverflow.

Aucun commentaire:

Enregistrer un commentaire