适配器模式的定义:
将一个类的接口转换成客户希望的另外一个接口。Adapter模式使得原来由于接口不兼容而不能一起工作的那此类可以一起工作
包括两种模式:
类适配器模式与对象适配器
类适配器:Adapter类与被适配类是继承关系
对象适配器:Adapter对象与被适配类对象是委托关系 , 委托关系就是通过构造函数或者方法传入被适配对象
PDOAdapter 继承 PDO类 , 扩展里面的方法 , 这就是类适配器模式
ArticleModel传入PDOAdapter 对象 , 扩展PDOAdapter 对象的方法 , 这就是对象适配器
<?php
//类适配器
class PDOAdapter extends PDO{
private $dsn = null;
private $username = null;
private $password = null;
private $timeout = 30;
private $charset = "utf8";
private $options = array(
PDO::ATTR_AUTOCOMMIT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
);
public function __construct($dsn, $username, $password, $timeout = null){
$this->dsn = $dsn;
$this->username = $username;
$this->password = $password;
$this->timeout = intval($timeout);
parent::__construct($dsn, $username, $password, $this->options);
$this->exec("set names ".$this->charset);
}
public function execute($sql, $params = array()){
$stmt = $this->prepare($sql);
$execStatus=$stmt->execute($params);
return $execStatus;
}
public function getAll($sql, $params = array()){
$stmt = $this->prepare($sql);
$stmt->execute($params);
return $stmt->fetchAll();
}
}
//对象适配器,使用委派
class ArticleModel{
private $pdo=null;
public function __construct($pdo){
$this->pdo=$pdo;
}
//委派调用PDOAdapter的getAll方法
public function getArticleList(){
$res=$this->pdo->getAll("select * from countries");
return $res;
}
}
class Controller{
public function doAction(){
try {
$pdo=new PDOAdapter("mysql:host=127.0.0.1;port=3306;dbname=phpfly","phpfly","phpfly");
$model=new ArticleModel($pdo);
$res=$model->getArticleList();
var_dump($res);
} catch (Exception $e) {
var_dump($e->getMessage());
}
}
}
$c=new Controller();
$c->doAction();