适配器模式,可以将截然不同的函数接口封装成统一的API
例如,PHP的数据库操作有mysql, mysqli, pdo 3种,可以用适配器模式统一成一致。类似的情景还有caceh适配器,将memcache, redis, file, apc等不同的缓存函数统一成一致。
//IDatabase.php 统一的接口
<?php
namespace App\Database;
interface IDatabase
{
function connect($host, $name, $password, $database);
function query($sql);
function close();
}
//MySQL.php MySQL类
<?php
namespace App\Database;
class MySQL implements IDatabase
{
protected $conn;
function connect($host, $name, $password, $database)
{
$conn = mysql_connect($host, $name, $password);
mysql_select_db($database, $conn);
$this->conn = $conn;
}
function query($sql)
{
return mysql_query($sql);
}
function close()
{
mysql_close($this->conn);
}
}
//MySQLi.php MySQLi类
<?php
namespace App\Database;
class MySQLi implements IDatabase
{
protected $conn;
function connect($host, $name, $password, $database)
{
$conn = mysqli_connect($host, $name, $password, $database);
return $this->conn = $conn;
}
function query($sql)
{
return mysqli_query($this->conn, $sql);
}
function close()
{
mysqli_close($this->conn);
}
}
//PDO.php PDO类
<?php
namespace App\Database;
class PDO implements IDatabase
{
protected $conn;
function connect($host, $name, $password, $database)
{
$dsn = "mysql:host=$host;dbname=$database";
$conn = new \PDO($dsn, $name, $password);
return $this->conn = $conn;
}
function query($sql)
{
return $this->conn->query($sql);
}
function close()
{
unset($this->conn);
}
}
//index.php 使用示例
<?php
use App\Database\MySQL;
$conn = new MySQL();
$conn->connect('127.0.0.1', 'root', '', 'test');
$res = $conn->query("show databases");
$conn->close();