在大話PHP設(shè)計模式中,這第六章講的真的是適配器嗎? 我自己參照網(wǎng)上寫了一個Mysql的適配器, 請大神幫看看是不是適配器模式的...
<?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);
2017-08-08
適配器的概念你可能沒有理解 ,舉個簡單的例子,session的緩存 可以由 file mysql redis memcache 多種實現(xiàn),但是為了session的操作 無非 set get ,適配器是定制一套統(tǒng)一的操作方法,由底層去實現(xiàn) 即為適配器