适配器模式
可以将截然不同的函数接口封装成统一的API
下面用数据库的连接来演示适配器模式,一下是每个php文件主要代码,省略部分代码,如:命名空间,类的自动加载等代码
定义一个database接口,mysql、mysqli、pdo三种连接数据库的方式统一继承这个接口
Database.php
<?php
/**
* 接口
*/
interface Database
{
function connect($host, $user, $passwd, $dbname);
function query($sql);
function close();
}
MYSQL.php
<?php
/**
* mysql方式连接数据库
*/
class MYSQL implements Database
{
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)
{
return mysql_query($sql, $this->conn);
}
function close()
{
mysql_close($this->conn);
}
}
MYSQLi.php
<?php
/**
* mysqli方式连接数据库
*/
class MYSQLi implements Database
{
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.php
<?php
/**
* PDO方式连接数据库
*/
class PDO implements Database
{
protected $conn;
function connect($host, $user, $passwd, $dbname)
{
$conn = new \PDO('mysql:host=$host;dbname=$dbname', $user, $password);
$this->conn = $conn;
}
function query($sql)
{
return $this->conn->query($sql);
}
function close()
{
unset($this->conn);
}
}
index.php
<?php
/**
* 调用以上三个数据库连接类型中一种
*/
$db = new ...\Database\数据库.php;
$db->connect('localhost', 'root', 'root', 'test');
$db->query('show databases');
$db->close();
兄弟写的非常好 https://www.cscnn.com/