1

I have read a book about MVC last week and a general one about design patterns, but I'm still confused as to where SQL queries belong in my code: the model or in the controller?

Let's take a very simple example, where you have a /popular page that will print the 5 most popular stories on a website.

In your model, you would have a class for prepared staments, and a class for assisting in the creation of the SELECT query. In your view, you'd have the HTML elements that display the /popular page.

Where does the query "SELECT most popular stories LIMIT 5" belong to? Is that something a controller class should ask, taking query methods from the model and passing to the view, or should the query be declared instead on a model class related to the /popular page?

Is the distinction even relevant? Would placing that query on the controller or the model be both considered professional ways to build a MVC?

Thank you. It seems most people get stuck understanding what to place on controllers

Edit: thanks for help everyone. Unfortunately as a new account I can't upvote any helpful posts yet

Rob
  • 21
  • 1
  • 5
  • The query code itself should go in the model (`getTopStories($count)`). If you want five of something, that sounds like it should go in your business logic, though you could hardwire it in the model, I suppose. In turn, business logic is a module that is called by your controller. You'll probably find it easier to understand this if you go through a good MVC tutorial (I don't know of one, but there is sure to be one out there). – halfer Sep 21 '14 at 16:17
  • 1
    You might find this post useful: http://stackoverflow.com/a/10685095/727208 (I really don't want to [mjölnir](http://meta.stackoverflow.com/questions/261456/update-help-center-to-include-the-mighty-mj%C3%B6lnir) this question single-handedly) – tereško Sep 22 '14 at 06:48

1 Answers1

0

Usually (based on my experiences with MVC frameworks) the model layer takes care of database-related stuff in MVC.

Consider following approach:

  1. Create abstract class which covers all the DB operations (selects, updates, etc). Each table would be a PHP class extending such class. You can then define DB table name in for instance private field, constructor or depending on model name.
  2. Each controller (or the single controller) would load desired model, and use its methods to fetch data as associative arrays or objects, delete the data, change it.
  3. After all DB operations have been done, controller returns view and passes data as its parameters.

Note that models are great place to put all the validation rules, and some helper methods due to the fact that they can be easily tested in PHPUnit.

Maciej Asembler
  • 656
  • 3
  • 5