Singleton Pattern with PDO?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
krz
Forum Newbie
Posts: 4
Joined: Mon Nov 01, 2004 9:44 am

Singleton Pattern with PDO?

Post 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?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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.
Post Reply