Well, if using a reasonably current version of PHP, you have the object-oriented [man]PDO[/man] database interface already built in, or the equally OO [man]mysqli[/man] interface if only concerned with MySQL. You can use these right out of "the box" just fine within an OOP application, or if needed you can extend them to add whatever special functionality you may need. For instance, you can make mysqli a "singleton" class (and also build your connection credentials right into it) with something like:
<?php
/**
* Database class to implement singleton pattern on top of mysqli
*/
class Database extends mysqli
{
/**
* @var object Singleton instance
*/
private static $instance = null;
// DB connection parameters:
private $dbHost = 'localhost';
private $dbUser = 'foobar';
private $dbPwd = 'password';
private $dbName = 'my_database';
/**
* Constructor
* @return void
*/
private function __construct()
{
@parent::__construct(
$this->dbHost,
$this->dbUser,
$this->dbPwd,
$this->dbName
);
if(mysqli_connect_errno())
{
throw new Exception(
mysqli_connect_error(),
mysqli_connect_errno()
);
}
}
/**
* Do the singleton thing
* @return object Database
*/
public function getInstance() {
if(self::$instance === null)
{
$c = __CLASS__;
self::$instance = new $c;
}
return self::$instance;
}
public function __clone()
{
throw new BookingException("Cannot clone ".__CLASS__." class");
}
}
Sample Usage:
<?php
require_once 'Database.class.php';
class Example
{
private $db;
public function __construct()
{
$this->db = Database::getInstance();
}
public function sampleMethod()
{
$result = $this->db->query('SELECT * FROM table');
if($result != false)
{
while($row = $result->fetch_assoc())
{
// do something with row data...
}
}
else
{
// handle query error here...
}
}
}