文件结构
DesignPattern
├── Drivers
│ ├── Db_Adapter.php
│ ├── MySQL.php
│ └── sqlite.php
├── index.php
└── sqlFactory.php
先定义一个接口
./Drivers/Db_Adapter.php
规定一些通用方法
<?php
interface Db_Adapter
{
public function connect($config);
}
定义了MySQL数据库的操作类
./Drivers/MySQL.php
这是一个实现了Db_Adapter接口的类。
<?php
include_once "Db_Adapter.php";
class Db_Adapter_MySQL implements Db_Adapter
{
private $_dbLink;
function __construct() {}
public function connect($config)
{
$this->_dbLink = @new mysqli($config['host'], $config["user"], $config["password"], $config["database"], $config['port']);
if ($this->_dbLink->connect_errno) {
echo "Failed to connect to MySQL: (" . $this->_dbLink->connect_errno . ") " . $this->_dbLink->connect_error;
}
return $this->_dbLink;
}
}
定义了SQLite数据库的操作类
./Drivers/sqlite.php
这是一个实现了Db_Adapter接口的类。
<?php
include_once "Db_Adapter.php";
class Db_Adapter_sqlite extends SQLite3 implements Db_Adapter
{
private $_dbLink;
function __construct() {}
public function connect($config)
{
try {
if ($this->_dblink = new SQLite3($config['database'] . '.db')) {
return $this->_dblink;
}
} catch (Exception $e) {
return $e->getMessage();
}
}
}
定义工厂类
sqlFactory.php
现在我们需要一个数据库操作的方法,只需要定义一个工厂类,根据传入不同的参数生成不同的类即可。
<?php
class sqlFactory
{
public static function factory($type)
{
if (include_once "Drivers/" . $type . ".php") {
$classname = 'Db_Adapter_' . $type;
return new $classname;
} else {
throw new Exception ('Driver not found');
}
}
}
工厂类如何使用
index.php
调用时,这么写就可以了。
<?php
include_once "sqlFactory.php";
$mysqlConfig = [
'host' => '10.160.5.28',
'port' => '3306',
'user' => 'root',
'password' => '123456!@#',
'database' => 'test',
'charset' => 'utf8mb4',
];
$sqliteConfig = [
'database' => 'mySQLite',
];
$db = sqlFactory::factory('MySQL');
$connect = $db->connect($mysqlConfig);
$db = sqlFactory::factory('sqlite');
$connect = $db->connect($sqliteConfig);