1

I just recently dove into OOP & now MVC and am using this template engine : http://www.milesj.me/resources/script/template-engine

I am curious about one question on where to put my DB calls (I'm using a basic database wrapper class).

I've seen two ways done.

class Cart

public static function count() {
    require_once(DATABASE .'cartext.php');
    $info = User::getInfo();
    $count = CartExt::inCart($info['0']['userid']);
    return $count;
}

Then in class CartExt

public static function inCart($shopperID) {
    $db = Database::getInstance();
    $query = $db->execute("SELECT * FROM Listing WHERE shopperid = '$shopperID'");
    $count = 0;
    while ($row = $db->fetchAll($query)) {
        $count++;
    }
    return $count;
}

With large functions I can see the advantage of separating the two, but a lot of the time it's as mundane as the example above, or worse: the base class just calls upon the Ext and returns its value! Also, I am doing a require_once from within the function to lower http requests if anyone is asking.

Anyway, I just want some thoughts on this.

Also, am I correct in that I should handle $_POST['data'] in the controller and pass it as an param to my functions there, opposed to handling it within the class? (I'm not using a form object/class yet if it matters).

Looking forward to hearing your thoughts on this.

Pradeep
  • 9,667
  • 13
  • 27
  • 34
asdfasdfasdfasdf
  • 462
  • 5
  • 17

1 Answers1

1

Database calls should be executed from the Model.
If this goes via:

  • mysql_query()
  • a database wrapper
  • an ORM like Doctrine

doesn't matter as far as MVC is concerned. Although I can recommend the latter.

Reasoning
When you are storing data in a database that data usually represents model data: a User, an Order, etc.

Exceptions
If your storing sessions in the database or use the database for caching. These belong more to the Controller than the Model classes.

Community
  • 1
  • 1
Bob Fanger
  • 28,949
  • 7
  • 62
  • 78