|  | Posted by amygdala on 04/16/07 14:01 
"Toby A Inkster" <usenet200703@tobyinkster.co.uk> schreef in bericht news:dclbf4-4kp.ln1@ophelia.g5n.co.uk...
 > amygdala wrote:
 >
 >> Since I would like to have only one database handler that can be accessed
 >> by
 >> both the constructor and the factory method (?) getUserById() I decided
 >> to
 >> declare $dbh static. Does this make sense?
 >
 > It makes sense, but a better solution would be to make your database
 > object into a singleton class. That is, similar to the Database object
 > here:
 >
 > http://message-id.net/<r1s3f4-4kp.ln1@ophelia.g5n.co.uk>
 >
 
 Well, that is the case already. Perhaps it was a bit confusion because I
 named the method in the Database object getInstance. I've changed it to
 getSingleton now. (See below).
 
 But that still doesn't allow me to create the $dbh only once at the
 beginning of the User class like so:
 
 class User
 {
 private $dbh = Database::getSingleton( /*  */ );
 
 private function __construct() {}
 
 public static function getUserById()
 {
 // use self::$dbh here
 }
 
 public function saveUser()
 {
 // use self::$dbh here
 }
 }
 
 Mind you, it's not a big issue, merely a cosmetic one. What I am still
 struggeling more with is the registrate function. Would you consider that a
 User class method. Or should it be in some other object. Or perhaps just be
 a regular function in the global script?
 
 
 // class Database code:
 
 class Database
 {
 protected static $dbh;
 
 private function __construct() {}
 
 public static function getSingleton( $interface, $host, $schema, $username,
 $password )
 {
 if ( !isset( self::$dbh ) )
 {
 self::$dbh = new PDO( ( $interface . ':host=' . $host . ';dbname=' .
 $schema ),  $username, $password );
 self::$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
 //self::$dbh->setAttribute( PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, TRUE );
 }
 return self::$dbh;
 }
 
 public function __destruct()
 {
 if ( isset( self::$dbh ) )
 {
 self::$dbh = NULL;
 }
 }
 }
 [Back to original message] |