seaweed Posted March 22, 2010 Share Posted March 22, 2010 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. Quote Link to comment https://forums.phpfreaks.com/topic/196078-connecting-in-a-pdo-database-class/ Share on other sites More sharing options...
ignace Posted March 22, 2010 Share Posted March 22, 2010 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. Quote Link to comment https://forums.phpfreaks.com/topic/196078-connecting-in-a-pdo-database-class/#findComment-1029885 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.