I am new to using classes in PHP, I just realized, in most of my class methods, I need to do some mysql queries. I have another class that handles my connection and queries but how should I go about calling that class from other classes? Doesn't this kind of defeat the purpose of using classes if all my classes rely on my DB class?
+1
A:
this is usually solved with the Singleton or Factory pattern...
when you need to use the db, you snatch the app's db object:
$db = Site::getDb(); // singleton
$db->exec('update t set i = i + 1');
getDb returns a static instance.
or:
$db = Db::getDb('dsn'); // factory
$db->exec('update t set i = i + 1');
returns a static instance if it exists, or creates a new db handle for that dsn...
jspcal
2010-01-14 04:44:13
+1, Nice answer, but don't you mean `Db::getDb()` instead of `Site::getDb()`?
Alix Axel
2010-01-14 04:54:26
sorry I am still learning this stuff, as I understand it, a singlton is used for the connection part, if as connection was already called/made then it uses that connection otherwise it creates a new one right? SO my main question here is based on what I have so far, I have a sessions class which sets and gets session variables for me instead of using the default set and get session features of PHP, I wrapped them in a class so I can change to use any kind of cache system down the road. I also have a database class which will make the connection and have methods for making queries. The way I
jasondavis
2010-01-14 18:52:31
see it is that I will need to have access to the database and session classes in all my other classes, I am just wanting to know if this is normal or not? Like let's say I decide to build a different site, if I try to use a "forums" class it will not work unless I bring over my database and session classes as well. I think this is OK but I am a total newbie with classes and such
jasondavis
2010-01-14 18:54:26