标签:
1.适配器模式:
能够将截然不同的函数接口封装成统一的API
2.实际应用举例,PHP的数据库操作有mysql, mysqli, pdo3种。能够用适配器模式统一成一致。相似的场景还有cache适配器,就是将memcache,redis,file,apc等不同的缓存函数统一成一致的
3.以下的样例能够帮助你对付各种数据库链接功能,mysql mysqli, pdo随便选,操作都抽象为统一的接口client不须要改动一行数据库链接方式
interface IDatabase
{
function connect($host, $user, $passwd, $dbname);
function query($sql);
function close();
}
class MySQL implements IDatabase
{
protected $conn;
function connect($host, $user, $passwd, $dbname)
{
$conn = mysql_connect($host, $user, $passwd);
mysql_select_db($dbname, $conn);
$this->conn = $conn;
}
function query($sql)
{
$res = mysql_query($sql, $this->conn);
return $res;
}
function close()
{
mysql_close($this->conn);
}
}
class MySQLi implements IDatabase
{
protected $conn;
function connect($host, $user, $passwd, $dbname)
{
$conn = mysqli_connect($host, $user, $passwd, $dbname);
$this->conn = $conn;
}
function query($sql)
{
return mysqli_query($this->conn, $sql);
}
function close()
{
mysqli_close($this->conn);
}
}
class PDO implements IDatabase
{
protected $conn;
function connect($host, $user, $passwd, $dbname)
{
$conn = new \PDO("mysql:host=$host;dbname=$dbname", $user, $passwd);
$this->conn = $conn;
}
function query($sql)
{
return $this->conn->query($sql);
}
function close()
{
unset($this->conn);
}
}
$db = new PDO();
$db->connect(‘127.0.0.1‘, ‘root‘, ‘root‘, ‘test‘);
$db->query(‘show databases‘);
$db->close();
$db = MySQLi ();
$db->connect(‘127.0.0.1‘, ‘root‘, ‘root‘, ‘test‘);
$db->query(‘show databases‘);
$db->close();
$db = MySQl PDO();
$db->connect(‘127.0.0.1‘, ‘root‘, ‘root‘, ‘test‘);
$db->query(‘show databases‘);
$db->close();
标签:
原文地址:http://www.cnblogs.com/mengfanrong/p/5183819.html