Jump to content

Connecting in a PDO Database Class


seaweed

Recommended Posts

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.

 

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.