I'm trying to understand how to use PDO with a "connection" class.
class db {
private static $dbh;
private function __construct(){}
private function __clone(){}
public static function connect() {
if(!self::$dbh){
self::$dbh = new PDO("mysql:host=localhost;dbname=database", "user", "password");
self::$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
return self::$dbh;
}
final public static function __callStatic( $chrMethod, $arrArguments ) {
$dbh = self::connect();
return call_user_func_array(array($dbh, $chrMethod), $arrArguments);
}
}
I've taken the above from http://php.net/manual/en/book.pdo.php, and modified the variables slightly but I'm wondering how I then connect to the PDO connection object within this db class?
$dbh = new db; //intiate connection???
$stmt = $dbh->prepare("SELECT * FROM questions WHERE id = :id"); // or should I do db::prepare.. ???
$stmt->bindParam(':id', $_GET['testid'], PDO::PARAM_INT);
if ($stmt->execute()) {
while ($row = $stmt->fetch()){
print_r($row);
}
}
Any ideas please? thanks
This is more or less how I do it. I'm not sure if this is the best way of doing it, but it works for me.
My factory class is the CORE of my code. From here I generate all classes I work with. My factory class is saved in a separate file
factory.class.php
.By having a factory class, I only need to include class files only once. If I did not have this, I would have to include my class files for each file having to use it. If I need to update a class file name later, I only need to make the update in factory class file.
Another reason for creating a factory object, was to reduce the number of DB connections.
I save each class as a separate file
Factory class
Connection class
Different class objects
These are your classes. This is where you work with your data In my own code I'm using tri-tier architecture, separating presentation, from business layer and data object layer.
Do the same for your other classes.
Putting it all together
Notice that we only include one file, the factory files. All other class files are included in Factory class file.
As i understood it, you want to have a "connection class" which implements lazy loading for the PDO instance. And then you want objects in your code to have access to that connection from every place in the code, effectively making a singleton.
Don't do it.
You are cleating a global state in your application and all your DB-enabled classes have tight coupling to the NAME of connection class.
I would recommend a bit different approach. As already @Steven hinted, you should use a factory to create objects, which require a DB connection.
Here is a simplified implementation.
You would use it kinda like this:
Now every time you execute
$factory->create('SomeClass')
, it will create a new instance of that class and provide it with proper DB connection in the constructor. And, when executed for the first time, it will open the connection to the DB.