I use a Singleton class that I usually call DatabaseManager
. By making a static public method called getDB()
, I never have to worry about passing the database around, as it will be available anywhere. Here's a brief stub:
class DatabaseManager
{
private static $instance;
private $db_connection;
public initDBConnection($connectionInfo) {
//make connection
}
public static function getInstance()
{
if (self::$instance == null) {
$className = __CLASS__;
self::$instance = new $className();
}
return self::$instance;
}
public static function getDB()
{
return self::getInstance()->db_connection;
}
}
Once you've initialized a database connection, you can simply call DatabaseManager::getDB()
to get the database connection.
The beauty of this approach is that it's easily extended to manage connections to multiple databases, as well as ensuring that you never have more than one connection open to any one database. Makes your connections very efficient.