Author Topic: Connecting in a PDO Database Class  (Read 1419 times)

0 Members and 1 Guest are viewing this topic.

Offline seaweedTopic starter

  • Enthusiast
  • Posts: 64
    • View Profile
Connecting in a PDO Database Class
« on: March 21, 2010, 11:13:44 PM »
I have a database class that uses PDO prepared statements. The connection is like this:

public function dbConnect() {
   $this->_dbh = new PDO('mysql:host=localhost; dbname=db_name', 'username', 'password');
}

I have a few questions about it.

1. Should I put this code in my constructor method?

2. Should I set $dbh = null; at the end of the script or leave it open?
    This application will be hammering this class with queries non-stop,
    it's the crux of the website, looking up products in a catalog.

Offline ignace

  • Guru
  • Freak!
  • *
  • Posts: 5,093
  • Gender: Male
    • View Profile
Re: Connecting in a PDO Database Class
« Reply #1 on: March 22, 2010, 04:39:05 AM »
1. Should I put this code in my constructor method?

No.

2. Should I set $dbh = null; at the end of the script or leave it open?
    This application will be hammering this class with queries non-stop,
    it's the crux of the website, looking up products in a catalog.

Db connections are automatically closed at the end of the script so you can't leave it open not even with the persistent option.

Plus you should be using something like:

class Db extends PDO implements Db_Interface

This decouples PDO from your models as the same could have been written:

class Db extends MySQLi implements Db_Interface

While your models only expect:

class MyModel {
    public function 
__construct(Db_Interface $db) {


Altough the above method (class Db extends ..) is not encouraged and an approach with a factory method and adapter pattern is encouraged

Also always remember to lazy-load:

interface Db_Interface {
    public function 
connect();
    public function 
query($sql);
}

class 
MyDb extends PDO implements Db_Interface {
    public function 
query($sql) {
        
$this->connect();
        
//..
    
}
}


A connection is made only when it is absolutly needed.
« Last Edit: March 22, 2010, 04:43:54 AM by ignace »
Developer from Belgium, Vlaams-Brabant