数据访问对象模式
该设计模式描述了如何创建提供透明访问任何数据源的对象.
// 这是一个单利模式用于提供mysql pdo链接
class MysqlConnect
{
protected $link = null;
protected static $instance = null;
public static function getInstance()
{
if (is_null(self::$instance)) {
self::$instance = new MysqlConnect();
}
return self::$instance;
}
protected function __construct()
{
$this->connect();
}
public function connect()
{
if (is_null($this->link)) {
$this->link = new PDO('mysql:host=127.0.0.1;dbname=test', 'root', 'root');
}
}
public function close()
{
$this->link = null;
}
public function getLink()
{
return $this->link;
}
}
abstract class DAO
{
protected $table = null;
protected $link = null;
public function __construct()
{
$this->link = MysqlConnect::getInstance()->getLink();
}
public function fetch()
{
$res = $this->link->query("SELECT * FROM {$this->table}");
$data = array();
foreach ($res as $row) {
$data[] = $row;
}
return $data;
}
}
class CD extends DAO
{
protected $table = 'cd';
}
$cd = new CD();
var_dump($cd->fetch());