Where do I put a database query in MVC?

前端 未结 5 1414
隐瞒了意图╮
隐瞒了意图╮ 2020-12-01 08:41

The last few days, I have extensively read books and web pages about OOP and MVC in PHP, so that I can become a better programmer. I\'ve come upon a little problem in my und

5条回答
  •  -上瘾入骨i
    2020-12-01 09:33

    For one, don't use mysql_query() and family; they're being deprecated, so consider also learning about PDO and/or mysqli.

    The model takes care of data handling; it provides an interface to the controller by which it retrieves and/or stores information. So this would be a primary place where database actions take place.

    Update

    To answer a question asked by the OP in the comments: "one generic model for the whole db or a model for each table/action?"

    Models are meant to abstract away individual tables (although there are models that exclusively handle a single table); for instance, instead of asking for all articles and then query the usernames for the authors you would have one function like this:

    function getArticles()
    {
        // query article table and join with user table to get username
    }
    

    How many models you will create largely depends on how big the project is and how inter-related the data is. If you can identify independent groups of data, it's likely that you'd create a model for each group; but this is no hard & fast rule.

    Data manipulation can be part of the same model, unless you want a clear separation between read-only and write-only models (I wouldn't know of a situation that warrants this, but who knows).

提交回复
热议问题