Here's the one I'm using:
<?php
final class Database {
private static $oDb;
public static function init() {
if(self::$oDb == NULL)
{
self::$oDb = mysql_connect('localhost', 'mysql_user', 'mysql_password') or die(mysql_error());
mysql_select_db('mysql_db_name', self::$oDb) or die (mysql_error());;
}
return self::$oDb;
}
public function query($sql)
{
return mysql_query($sql) or die(mysql_error());
}
}
?>
Usage:
$oDb = Database::init();
$sql = foo;
$oDb->query($sql);
Assuming that I only want it to connect and execute this one query function, are there any improvements I should make on the class? Memory or efficiency of code?
Also, is there an efficient way I can get the db credentials from a config file? I know I can't use includes inside my class.
For singleton classes, the model that Dan Breen followed is cleanest and very common. However, in this case, I would also allow the
getInstance
method to accept some parameters so that you can override your default configuration at instantiation time, or just get a reference without creating a connection (both use-cases happen from time to time).Database.php
..config/database.php:
Edit: I've changed it to act more like a flyweight to ensure that you only get one instance for each connect location/database. This addresses your concerns and maintains a degree of flexibility.
You can use an include inside a function inside a class
or you can just pass the variables...
or you can store the credentials in a php.ini file
php.ini file:
I usually use lazy initialization for this sort of situation and only have one public method (in this case), with a private constructor to prevent outside instantiation (per the Singleton pattern):
Then you can just call
$dbHandle = Database::getInstance()
anytime you need to use it. Or in this case since a static query method is defined, you can useDatabase::query("select * from xx;");
without having to call any sort of init at all.That's a simple as it gets, that will work fine.
You can pass your credentials to init();