作者:手机用户2502907673 | 来源:互联网 | 2017-05-13 02:18
适配器模式,可以将截然不同的函数接口封装成统一的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) {
returnmysqli_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();
以上就介绍了php设计模式 适配器模式,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。