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
https://forums.phpfreaks.com/topic/196078-connecting-in-a-pdo-database-class/
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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.