適配器模式,可以將截然不同的函數接口封裝成統一的API;
應用舉例,PHP的數據庫操作有Mysql、Mysqli、pdo三種,可以用適配器模式統一成一致,類似的場景還有cache適配器,將memcache、redis,file,apc等不同的緩存函數統一成一致。
IDatabase.php
<?php namespace Baobab; interface IDatabase{ function connect($host, $user, $passwd, $dbname); function query($sql); function fetch_result($result); function close(); }
Mysqli.php
<?php namespace Baobab\Database; use Baobab\IDatabase; class Mysqli implements IDatabase{ protected $conn; function connect($host, $user, $passwd, $dbname){ $conn = mysqli_connect($host, $user, $passwd, $dbname); mysqli_set_charset($conn, 'utf8'); $this->conn = $conn; } function query($sql) { return mysqli_query($this->conn, $sql); } function fetch_result($result){ return mysqli_fetch_all($result); } function close() { mysqli_close($this->conn); } }
Pdo.php
<?php namespace Baobab\Database; use Baobab\IDatabase; class Pdo implements IDatabase{ protected $conn; function connect($host, $user, $passwd, $dbname){ $conn = new \PDO("mysql:dbname=$dbname;host=$host", $user, $passwd); $this->conn = $conn; } function query($sql){ return $this->conn->query($sql); } function fetch_result($result){ } function close() { unset($this->conn); } }
index.php
$db = new Baobab\Database\Mysqli(); $db->connect('127.0.0.1', 'root', '', 'test'); $res = $db->query('select * from ha_cl'); print_r($db->fetch_result($res)); $db->close();