标签:
① 适配器模式可以将截然不同的函数接口封装成统一的 API
② 实际应用举例:PHP 的数据库操作有 mysql,mysqli,pdo 三种,可以用适配器模式统一成一致。类似的场景还有 cache 适配器,将 Memcache,Redis,file,apc 等不同的缓存函数,统一成一致
代码实现:
在 Common 下建立 Database 文件夹,创建三个 PHP 文件来表示三种不同的数据库操作函数:MySQL.php,MySQLi.php,PDO.php,这三个文件都使用适配器模式,在 Common 下简历 IDatabase.php,用来封装接口:
在 Common/Database.php 中首先定义接口,用接口约定适配器的行为:
IDatabase.php
<?php namespace Common; interface IDatabase{ //连接操作 function connect($host, $user, $passwd, $dbname); //执行一条SQL语句 function query($sql); //关闭连接 function close(); }
MySQL.php:
<?php namespace Common\Database; use Common\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); } }
入口文件 index.php:
<?php define(‘BASEDIR‘,__DIR__); //定义根目录常量 include BASEDIR.‘/Common/Loader.php‘; spl_autoload_register(‘\\Common\\Loader::autoload‘); $db = new Common\Database\MySQL(); $conn = $db->connect(‘127.0.0.1‘, ‘root‘, ‘‘, ‘crm‘); $res = $db->query(‘select uid from crm_user‘); while($rows = mysql_fetch_assoc($res)){ echo $rows[‘uid‘],‘<br>‘; } $db->close($conn);
页面输出(查询结构):
268772 268857 268858 268859 268860 268861 268862 268863 268864 268866 268867 268868 268869 268870 268871 268872
MySQLi.php(mysqli 和 mysql 的函数很类似)
<?php namespace Common\Database; use Common\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){ $res = mysqli_query($this->conn, $sql); return $res; } function close(){ mysql_close($this->conn); } }
PDO.php
<?php namespace Common\Database; use Common\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); } }
标签:
原文地址:http://www.cnblogs.com/dee0912/p/4417247.html