phpdesign-patternsdatabase-abstraction

php shared db connection ( design pattern help )


I have a small php app that I want to build a layer of db abstraction on top of with a few "model" type classes.

I'm using ezSQL_mysql to do the db work.

My question is what is the best way to design the app? Should I use a singleton pattern to share the db connection? Should my "model" classes extend ezSQL_mysql ? Or maybe I'm totally off base here and need to do something else.

What I need is something like this

Controller.php

   $db = new ezSQL_mysql($db_user, $db_passwd, $db_database, $db_host);


   $user = new User();
   $user->update_email($new_email);

   $sale = new Sale();
   $sale->purchase($amount); 

User_model.php

class User {

   /* uses $db connection */
   function update_email(){
     /* do something */
   };
}

Sale_model.php

class Sale {   
   /* uses $db connection*/

   function purchase () {
    /* do something */ 
   }
}

Solution

  • Okay... so the small app's requirements grew, as per usual and I decided to go with an MVC framework, rather than rolling my own loose set of classes to manage a persistant connection and abstract the database layer.

    So now I'm using CodeIgniter http://www.codeigniter.com/ which basically accomplishes what I wanted to do in a easier to manage fashion.

    Thanks for the other answers.