Accessing database class

Codes here !

Moderators: macek, egami, gesf

Post Reply
User avatar
ejsexton82
New php-forum User
New php-forum User
Posts: 86
Joined: Mon Jun 04, 2012 10:05 pm
Location: Ankara, Turkey
Contact:

Re: Accessing database class

Post by ejsexton82 » Sat Jun 09, 2012 3:52 am

You could turn your database object into a "singleton":

Code: Select all

class DatabaseObject {
	protected $id;
	
	protected static $instance;
	
	protected function __construct() {
		$this->id = uniqid();
	}
	
	public function getId() {
		return $this->id;
	}
	
	public static function &getInstance() {
		if(!isset(self::$instance)) {
			$class = get_class();
			self::$instance = new $class();
		}
		return self::$instance;
	}
}
Then to access your database object, all you would have to do is call getInstance():

Code: Select all

class One {
	public function __construct() {
		$db = DatabaseObject::getInstance();
		echo "<p>Database Instance #{$db->getId()}</p>";
		$db->one = "Accessed by Class One";
	}
}

class Two {
	public function __construct() {
		$db = DatabaseObject::getInstance();
		echo "<p>Database Instance #{$db->getId()}</p>";
		echo "<p>{$db->one}</p>";
	}
}

$one = new One();
$two = new Two();

NigelRen
php-forum Fan User
php-forum Fan User
Posts: 610
Joined: Fri Aug 05, 2011 9:53 am

Re: Accessing database class

Post by NigelRen » Fri Jun 15, 2012 1:22 pm

'A better way' is almost always a matter of opinion. If you use a singleton then you remove a lot of the passing the database connection around, but you also limit the flexibility of your code. What happens if you want to use another connection for some reason?
If you consider something like mysql_query - in it's simplest form it uses the 'currently active database' which is fine till someone else changes the sequence of the code and suddenly code that has worked for ages falls over.
If you always specify the database/connection you want to use then you know what it should be accessing and you can see how it's being used.

Post Reply

Who is online

Users browsing this forum: Google [Bot] and 5 guests