首页 > 代码库 > 适配模式
适配模式
定义:可以将截然不同的函数接口封装成统一的API
实际应用举例:1.PHP的数据库有mysql,mysqli,pdo3种,可以用适配器模式统一成一致
2.cache适配器,将memcache,redis,file,apc等不同的缓存函数,统一成一致
以实际应用举例1作为示例
$db = new IMooc\Database\MySQL();
//$db = new IMooc\Database\MySQLi();
//$db = new IMooc\Database\PDO();
$db->connect(‘127.0.0.1‘, ‘root‘, ‘root‘, ‘test‘);
$db->query("show databases");
$db->close();
<?php
namespace IMooc;
interface IDatabase
{
function connect($host, $user, $passwd, $dbname);
function query($sql);
function close();
}
<?php
namespace IMooc\Database;
use IMooc\IDatabase;
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);
}
}
<?php
namespace IMooc\Database;
use IMooc\IDatabase;
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);
}
}
<?php
namespace IMooc\Database;
use IMooc\IDatabase;
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);
}
}
来自为知笔记(Wiz)
适配模式
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。