Board index   FAQ   Search  
Register  Login
Board index php forum :: Database mySQL & php coding

Accessing database class

Codes here !

Moderators: macek, egami, gesf

Accessing database class

Postby phpdrinker » Fri Jun 08, 2012 8:52 am

Hey, I was wondering whats the best way to access a database object from other objects. I have searched alot to find an answer but the best answer I have got is "pass the database object into your other objects in their constructors" but I was thinking that there must be a better way? Any opinions would be great thanks!
phpdrinker
New php-forum User
New php-forum User
 
Posts: 1
Joined: Fri Jun 08, 2012 8:43 am

Re: Accessing database class

Postby 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();
User avatar
ejsexton82
New php-forum User
New php-forum User
 
Posts: 86
Joined: Mon Jun 04, 2012 10:05 pm
Location: Ankara, Turkey

Re: Accessing database class

Postby 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.
NigelRen
php-forum Active User
php-forum Active User
 
Posts: 450
Joined: Fri Aug 05, 2011 9:53 am


Return to mySQL & php coding

Who is online

Users browsing this forum: No registered users and 1 guest

Sponsored by Sitebuilder Web hosting and Traduzioni Italiano Rumeno and antispam for cPanel.