An example php code with static creation:
interface DbTable
{
public function doSomething(): void;
}
class MySqlTable implements DbTable
{
public function doSomething(): void
{ }
}
class OracleTable implements DbTable
{
public function doSomething(): void
{ }
}
class TableFactory
{
public static function createTable(string $type = null): DbTable
{
if ($type === 'oracle') {
return new OracleTable();
}
return new MySqlTable(); // default is mysql
}
}
// client
$oracleTable = TableFactory::createTable('oracle');
$oracleTable->doSomething();
To make it more dynamic (less modification later):
interface DbTable
{
public function doSomething(): void;
}
class MySqlTable implements DbTable
{
public function doSomething(): void
{ }
}
class OracleTable implements DbTable
{
public function doSomething(): void
{ }
}
class TableFactory
{
public static function createTable(string $tableName = null): DbTable
{
$className = __NAMESPACE__ . $tableName . 'Table';
if (class_exists($className)) {
$table = new $className();
if ($table instanceof DbTable) {
return $table;
}
}
throw new \Exception("Class $className doesn't exists or it's not implementing DbTable interface");
}
}
$tbl = TableFactory::createTable('Oracle');
$tbl->doSomething();