The approach I would take would be something like the following. First I would create an interface to hold all the child class methods that I'll be needing for my database class:
php Code:
interface Database_Interface
{
public function insertRow($aData);
public function updateRow($aData, $iRowId);
public function deleteRow($iRowId);
}
Then I would create the child classes, one for each single database type possible, which all implement that interface:
php Code:
class Database_PostgreSQL implements Database_Interface
{
public function insertRow($aData) { return 'Insert PostgreSQL'; }
public function updateRow($aData, $iRowId) { return 'Update PostgreSQL'; }
public function deleteRow($iRowId) { return 'Delete PostgreSQL'; }
}
class Database_MySQL implements Database_Interface
{
public function insertRow($aData) { return 'Insert MySQL'; }
public function updateRow($aData, $iRowId) { return 'Update MySQL'; }
public function deleteRow($iRowId) { return 'Delete MySQL'; }
}
class Database_MySQLi implements Database_Interface
{
public function insertRow($aData) { return 'Insert MySQLi'; }
public function updateRow($aData, $iRowId) { return 'Update MySQLi'; }
public function deleteRow($iRowId) { return 'Delete MySQLi'; }
}
And finally add the database base which would be the class that's first initialised:
php Code:
class Database
{
private $m_pDatabase;
public function setDatabase(Database_Interface $pDatabase)
{
$this->m_pDatabase = $pDatabase;
}
public function insertRow($aData)
{
return $this->m_pDatabase->insertRow($aData);
}
public function updateRow($aData, $iRowId)
{
return $this->m_pDatabase->updateRow($aData, $iRowId);
}
public function deleteRow($iRowId)
{
return $this->m_pDatabase->deleteRow($iRowId);
}
}
Then last of all we would initialise that class we've just created, and set the database we want to use by using the
setDatabase function. By doing that, we can seamlessly change database types, as the majority of the code is kept in the child classes.
php Code:
$pDb =
new Database
();
$pDb->
setDatabase(new Database_PostgreSQL
());
echo $pDb->
insertRow(array(1,
2));
As we have set the database type to PostgreSQL, any function calls will be routed to the PostgreSQL child class. Voila!