Darkspirit暗灵
2017-08-04 13:15
<?php
class MysqlAdapter{
protected $host;
protected $uname;
protected $passwd;
protected $dbname;
public function __construct($host,$uname, $passwd, $dbname)
{
$this->host = $host; $this->uname=$uname;
$this->passwd = $passwd; $this->dbname=$dbname;
}
public function Adapt($adaptee){
return new $adaptee($this->host,$this->uname, $this->passwd, $this->dbname);
}
}
class MysqlAdaptee {
protected $link;
function __construct($host, $username, $password, $databaseName)
{
$conn = mysqli_connect($host, $username, $password, $databaseName);
$this->link = $conn;
if($this->link) echo "Login success!";
else echo "Login failed!";
}
function query($sql)
{
return mysqli_query($this->link, $sql);
}
function close()
{
mysqli_close($this->link);
}
}
$MysqlAdapter = new MysqlAdapter("localhost","root","123456","test");
$link = $MysqlAdapter->Adapt(MysqlAdaptee::class);
$result = $link->query("show databases");
$data = mysqli_fetch_all($result);
var_dump($data);
适配器的概念你可能没有理解 ,举个简单的例子,session的缓存 可以由 file mysql redis memcache 多种实现,但是为了session的操作 无非 set get ,适配器是定制一套统一的操作方法,由底层去实现 即为适配器
大话PHP设计模式
62160 学习 · 230 问题
相似问题