PHP设计模式之适配器模式
- 概念:将各种截然不同的函数接口封装成统一的API。
- 使用场景:PHP中的数据库操作有MySQL,MySQLi,PDO三种,可以用适配器模式统一成一致,使不同的数据库操作,统一成一样的API。类似的场景还有cache适配器,可以将memcache,redis,file,apc等不同的缓存函数,统一成一致。
<?php
interface IDatabase
{
function connect($host, $user, $passwd, $dbname);
function query($sql);
function close();
}
//mysql
class MySQL implements IDatabase
{
protected $conn;
function __construct($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);
}
}
//mysqli
class MySQLi implements IDatabase
{
protected $conn;
function __construct($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);
}
}
$Mysql = new MySQL($host, $user, $passwd, $dbname);
$mysqli = new MySQLi($host, $user, $passwd, $dbname);