Page 1 of 1

Singleton Pattern with PDO?

Posted: Sun Oct 16, 2005 8:25 am
by krz
php:

Code: Select all

class DBMgr { 

    protected $objDatabase;                    // Object is protected and can only be accessed by the class itself and any child classes
    private static $instance;            // Hold an instance of the class. Declared as a static variable, because the value is expected to remain static. It is used in the singleton function to check, whether the var has been set
  
    // A private constructor; prevents direct creation of object
    private function __construct($dbuser = 'usr', $dbpass = 'pwd') {
    
        try { $this->objDatabase = new PDO("mysql:host=localhost;dbname=dbname", $dbuser, $dbpass); }      // Connect to the db
        catch( PDOException $e ) { die( $e->getMessage() ); }                     // If any errors found, report them
      
    }

   // The singleton method
    public static function singleton() {
      if (!isset(self::$instance)) { self::$instance = new DBMgr(); }
      return self::$instance;
    }
}


//-----------------------------------------

require_once('class.DBMgr.php');

class Product extends DBMgr { 
    
  // Private variables can only be accessed by the class
  private $dbProperties;        // Properties from database
  private $postProperties;      // Properties from post

  // Initialise object
  function __construct($id) {

    parent::__construct();
    var_dump($this->objDatabase);
    
    $databaseProperties = $this->objDatabase->query("SELECT * FROM product WHERE productID = $id");
    print_r($databaseProperties);

        }
}

?>
?>


Isn't this a singleton pattern already? i dont even need to call singleton(). all i do is call DBMgr::__construct in the child class (Product) and $objDatabase is assigned a new instance of PDO.

If i call DBMgr::__construct again, it wont create a second instance instead it will override $objDatabase. so infact, there is no need for the singleton function, right?

For example: I call DBMgr::__construct 4 times. only one instance of $objDatabase will be created. Therefore, there is only once connection to the database.

Or am I missing the point somewhere?

Posted: Sun Oct 16, 2005 10:37 am
by feyd
if you want it as a singleton, you must set the child class' constructor to private as well, thereby only allowing the singleton to create the instance.