Can a Controller have database queries (MySQL)? If

2019-06-26 17:05发布

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?

4条回答
何必那么认真
2楼-- · 2019-06-26 17:24

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.

查看更多
聊天终结者
3楼-- · 2019-06-26 17:29

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

查看更多
走好不送
4楼-- · 2019-06-26 17:34

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

查看更多
小情绪 Triste *
5楼-- · 2019-06-26 17:39

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.

查看更多
登录 后发表回答