开发者

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

开发者 https://www.devze.com 2023-04-01 07:11 出处:网络
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

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.开发者_Python百科 ?

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.


Technically - yes, it is possible. But it would break the whole idea behind MVC.


In my software, I'm making it possible to extract query objects from model and execute them from inside controllers:

$model->dsql()->where('age>',20)->do_delete();

So technically - yes, controller can execute queries, but it must rely on the model to build that query.

0

精彩评论

暂无评论...
验证码 换一张
取 消