用单列模式写一个链接数据库的例子
<?php
// http://php.net/manual/zh/book.pdo.php
class DB {
private static $dbInstance;
private $dbCon;
private function __construct() {
try {
$dbConf = self::getConf();
$this->dbCon = new PDO($dbConf['dsn'], $dbConf['username'], $dbConf['password']);
} catch (PDOException $e) {
die('Could not connect: ' . $e->getMessage());
}
}
public static function getInstance() {
if (!(self::$dbInstance instanceof self)) {
self::$dbInstance = new self();
}
return self::$dbInstance;
}
public function __clone() {
throw new Exception("Can't clone");
}
public function getDbCon()
{
return $this->dbCon;
}
// return arr
public function select() {
$stmt = $this->getDbCon()->prepare("select * from users limit 1");
$stmt->execute();
return $stmt->fetchAll();
}
public static function getConf()
{
return $dbConf = [
'dsn' => 'mysql:dbname=blog;host=127.0.0.1',
'username' => 'root',
'password' => 'password'
];
}
}
$db = DB::getInstance();
$rows = $db->select();
var_dump($rows);
在建立数据库连接之前检查数据库连接是否已经存在,也就是说同一个客户端请求连接数据库只实例化一次,避免了多次链接数据库导致内存增长。
单列模式必须满足, private __construct, private instance, can't clone, public getInstance. 只能通过getInstance方法获取实例。
使用单列模式类似的场景有:
记录log的类,战争游戏项目中某个大类的英雄,某个大类的API初始化。
网友评论