Maintain a single DB object (singleton pattern?)
Posted: Mon Sep 07, 2009 2:36 am
I'm coding a DB class to manage all the MySQL operations. In my projects I need to use a single object of this class to query the database. My problem is the "visibility" of the DB object variable, that is:
A (bad) solution can be using global $db inside the functions, bad if I change the variable name... A (good) solution seems to be the singleton pattern:
http://www.ultramegatech.com/blog/2009/ ... n-pattern/
I have made a similar thing:
Is there a better solution? Maybe that don't need an instruction ($db = DB::get()) at the beginning of every function? How do you do in this cases?
Thank you all...
Code: Select all
// Create DB object
$db = new DB();
// Here I can use the global variable
$db->query("SELECT * FROM table");
// But inside a function or a class method
function my_function() {
// Here $db is obviously not visible! :(
} http://www.ultramegatech.com/blog/2009/ ... n-pattern/
I have made a similar thing:
Code: Select all
class DB() {
private static $last_db = null;
public function __construct() {
// mysql_connect(); etc...
self::$last_db = $this; // store last object created
}
public static function get() {
if (is_null(self::$last_db)) throw new Exception('DB: no database opened');
return self::$last_db;
}
}
// And now in my functions I can do
function my_function() {
$db = DB::get();
$db->query("SELECT * FROM table");
}Thank you all...