I am reading lots of tutorials on MVC, so my question, can a perfect PHP MVC framework have database queries in Controller? As I understand, the most comfortable way is to put all database queries in Model, right? And if I have POST or smth, I just pass that POST to Model and it makes all inserts and etc. ?
Or I am missing something? And if Controller can have a database queries, in which situation would it be?
No controller may not have any db related code - any DB queries may be stored in model in MVC architecture - controller only works with models, but not directly with DB
EDIT: Most frameworks will allow calling SQL directly from Controller - but then it is not MVC, but bunch of objects
No Controller must not IDEALLY and CONCEPTUALLY contain any database queries. If you have some queries in the controller itself then it will take away some key advantages of the MVC architecture such as Code Segregation and so on.
Ideally your, Model Classes (M) must contain DB queries and any interactions with DB via DB objects. A model ideally represents a Table in the DB or a file used for io
Views (V) must contain HTML with very little PHP. In most conditions only loops and conditional statements are used
Controller Classes (C) must contain all the business logic of you application, error handlers and so on.
It is very useful to maintain the MVC Architecture in regards to Maintain, Debug and also code understanding form a new developers prospective. The norms bring in a lot of benefits as mentioned above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With