tags:

views:

71

answers:

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

    /**
 * Counts items in cart
 * @return int
 */
public static function count() {
 require_once(DATABASE .'cartext.php');
 $info = User::getInfo();
 $count = CartExt::inCart($info['0']['userid']);
 return $count;
}

Then in class CartExt

/**
 * user cart count
 * @param int
 * @return int
 */
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.

+1  A: 

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.

Bob Fanger