garry Posted November 13, 2008 Share Posted November 13, 2008 I'm trying to put together a series of classes using OOP to make it easier to make the dynamic site I'm building. Basically, I have the following classes at the moment (more might be added later) Database Session User Validate I want to set it up so that all queries go through the database class (ie $db->query($sql). But I'm having trouble getting it all to work with each other (I'm new to OOP). To make all queries go through the database, should i create a new Database object for each query? Or is this bad practice? Also, I was wondering what the best way to handle the actual link to the database is. Because I was getting too many connections open errors. How can I only create the mysqli object with the connection once and then use it every time the database object is called? I'd really appreciate some help Thanks Quote Link to comment Share on other sites More sharing options...
corbin Posted November 13, 2008 Share Posted November 13, 2008 You're probably best off with a registry in which you store an instance of the database class. This is the basic flow of my database class (although it uses what I call an "internal registry ;p"). (Someone helped me with this a while back, so if you recognize it, that's why. Sorry for not crediting you, but I don't remember x.x.) CDB::RegisterConfig(array('main' => array('host' => 'localhost', 'user' => 'root', 'password' => 'root', 'database' => 'blah'))); CDB::GetInst('main')->query(); Quote Link to comment Share on other sites More sharing options...
garry Posted November 13, 2008 Author Share Posted November 13, 2008 Thanks for your reply. Was wondering if you could show me the basic gist of your registry class? And also, how it gets called on each page? Quote Link to comment Share on other sites More sharing options...
corbin Posted November 13, 2008 Share Posted November 13, 2008 public static function RegisterConfig($c) { self::$configs = array_merge(self::$configs, $c); return true; } public static function GetDB($w = 'main') { static $insts = array(); if(!isset($insts[$w])) { $insts[$w] = CDB::GetNew($w); } return $insts[$w]; } Like I said, it's not, by definition, anything like a registry, but it serves a similar purpose. GetDB just creates an instance based on the config passed into RegisterConfig, or if the instance already exists, it returns it. Someone better at OOP than I can probably come up with a better solution. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.