Where to put queries?

So I’m still new to MVC, and I understand that the model is the one responsible to ‘talk’ with the storage, in this case the database.

I have several costume queries and I placed all of them on the module class, but using the find(), findOne() or select()->from()->(…) functions I place them in the controller.

Am I doing this right? My brother, that is studying IT Engineering said that, technically/theoretically I shouldn’t put the queries on the module class, so at this point I’m not sure if I am doing this right :P

anyone up to help me with this? :)

I think it’s good to put it in Controller and model not in module.

This queries should be in models , I think.


try to put queries within your Model just to keep your controller clean and easy to read. Once you have a lot of queries within your Model, think about moving it to another place, like another class for example. This other class could be a repository or DAO.

Thank you for your answers, and thank you for reinforcing that I was somewhat right :P

Thiago, can you explain what DAO is? thank you.

To keep things organized, if you have a model named Student, create another class named StudentDAO. Within StudentDAO you can have methods named like findAll, findByName and others… so you will add your queries within these methods.

Maybe the name DAO is not good ('cause DAO already is within yii2 API), but what you need is a class where you put queries in to keep your model clean. If you name the class that will have your queries as StudentRepository, StudentData for example, you probably have better names.

If I were you I would start adding queries within the models. If system get too complex with too much queries, try to learn something about the Repository design pattern, so I would move queries to the class StudentRepository.

(obs: DAO means Data Access Object, so I suggested it as an abstraction for your calls to the database)