1.说明
1.适配器模式:
2.实际应用举例,PHP的数据库操作有mysql, mysqli, pdo3种。能够用适配器模式统一成一致。相似的场景还有cache适配器,就是将memcache,redis,file,apc等不同的缓存函数统一成一致的 3.以下的样例能够帮助你对付各种数据库链接功能,mysql mysqli, pdo随便选,操作都抽象为统一的接口client不须要改动一行数据库链接方式能够将截然不同的函数接口封装成统一的API
2.创建一个接口
interface IDatabase{ function connect($host, $user, $passwd, $dbname); function query($sql); function close();}
3.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); }}
4.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); }}
5.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); }}
6.实例调用,(统一接口调用)
$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();