Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a Controller have database queries (MySQL)? If yes, when?

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?

like image 340
good_evening Avatar asked Dec 04 '22 20:12

good_evening


2 Answers

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

like image 175
SergeS Avatar answered Dec 07 '22 09:12

SergeS


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.

like image 34
Sourabh Narayankar Avatar answered Dec 07 '22 08:12

Sourabh Narayankar