I have a few classes that perform some MySQL queries and prepared statements. However, I am lost in how to incorporate my PDO object within those classes. For example, I want to do something like this:
<?php
$dbh = new PDO(...);
class Foo extends PDO {
public $dbh;
public function bar() {
$this->dbh->prepare('SELECT * FROM table');
$this->dbh->execute();
}
}
?>
Unfortunately, it doesn't work. Can anyone suggest an elegant way to do this? Thanks for your time. Sorry I'm new to this, please leave any comments if you are unclear about anything and I'll do my best to respond!
Source: Tips4all
You can instantiate your connection to the database in a class that implement the singleton pattern.
ReplyDeleteThe connection will be done once and this class will be easily accessible by all of your other objects / scripts.
i use a class called "Core" in the following example;
class Core
{
public $dbh; // handle of the db connexion
private static $instance;
private function __construct()
{
// building data source name from config
$dsn = 'pgsql:host=' . Config::read('db.host') .
';dbname=' . Config::read('db.basename') .
';port=' . Config::read('db.port') .
';connect_timeout=15';
// getting DB user from config
$user = Config::read('db.user');
// getting DB password from config
$password = Config::read('db.password');
$this->dbh = new PDO($dsn, $user, $password);
}
public static function getInstance()
{
if (!isset(self::$instance))
{
$object = __CLASS__;
self::$instance = new $object;
}
return self::$instance;
}
// others global functions
}
this class take parameters from a static class called "Config" where you can store your configuration:
<?php
class Config
{
static $confArray;
public static function read($name)
{
return self::$confArray[$name];
}
public static function write($name, $value)
{
self::$confArray[$name] = $value;
}
}
// db
Config::write('db.host', '127.0.0.1');
Config::write('db.port', '5432');
Config::write('db.basename', 'mydb');
Config::write('db.user', 'myuser');
Config::write('db.password', 'mypassword');
in all your scripts / objects you just have to get the instance of Core and then query the DB
$sql = "select login, email from users where id = :id";
try {
$core = Core::getInstance();
$stmt = $core->dbh->prepare($sql);
$stmt->bindParam(':id', $this->id, PDO::PARAM_INT);
if ($stmt->execute()) {
$o = $stmt->fetch(PDO::FETCH_OBJ);
// blablabla....
If you need more information about singleton look at the PHP doc http://php.net/manual/en/language.oop5.patterns.php
$dbh isn't within the scope of Foo, do this instead:
ReplyDeleteclass Foo /*extends PDO*/
{
public $dbh;
public function __construct()
{
$dbh = new PDO(/*...*/);
}
public function bar()
{
$this->dbh->prepare('SELECT * FROM table');
return $this->dbh->execute();
}
}
Also, Foo doesn't need to extend PDO.