php设计模式 适配器模式,php设计模式_PHP教程
程序员文章站
2024-04-05 13:26:06
...
php设计模式 适配器模式,php设计模式
适配器模式,可以将截然不同的函数接口封装成统一的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();