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(); }
mysql封装
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); } }
mysqli封装
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); } }
pdo封装
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();