<?php
// 单例模式封装最终的pdo类
namespace Frame\Vender;
use \PDO;
use \PDOException;
final class PDOWrapper{
// 私有的静态的存储对象的属性
private static $instance=null;
private $db_type; //数据库类型
private $db_host; //主机名
private $db_port; //端口号
private $db_user; //用户名
private $db_pass; //密码
private $charset; //字符集
private $db_name; //数据库名
private $pdo;
//私有的构造方法
private function __construct(){
$this->db_type = $GLOBALS['config']['db_type'];
$this->db_host = $GLOBALS['config']['db_host'];
$this->db_port = $GLOBALS['config']['db_port'];
$this->db_user = $GLOBALS['config']['db_user'];
$this->db_pass = $GLOBALS['config']['db_pass'];
$this->db_name = $GLOBALS['config']['db_name'];
$this->charset = $GLOBALS['config']['charset'];
// 连接数据库
$this->connectPdo();
//设置pdo报错模式
$this->setErrMode();
}
// 私有的克隆方法
private function __clone(){}
// 公共的静态的用于创建对象的方法
public static function getInstance(){
if (!self::$instance instanceof self) {
self::$instance = new self();
}
return self::$instance;
}
private function connectPdo(){
try {
$dsn = "{$this->db_type}:host={$this->db_host};port={$this->db_port};";
$dsn .= "dbname={$this->db_name};charset={$this->charset}";
$this->pdo = new PDO($dsn,$this->db_user,$this->db_pass);
} catch (PDOException $e) {
echo '<h1>创建pdo对象失败</h1>';
echo '<br>错误编号'.$e->getCode();
echo '<br>错误行号'.$e->getLine();
echo '<br>错误文件'.$e->getFile();
echo '<br>错误信息'.$e->getMessage();
}
}
//设置pdo报错级别
private function setErrMode(){
$this->pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
}
//私有的的数据库查询方法
private function query($sql){
try {
return $this->pdo->query($sql);
} catch (PDOException $e) {
$this->showErr($e);
}
}
//公共的数据库执行操作
public function exec($sql){
try {
return $this->pdo->exec($sql);
} catch (PDOException $e) {
$this->showErr($e);
}
}
//获取单行数据
public function fetchOne($sql){
$PDOStatement = $this->query($sql);
return $PDOStatement->fetch(PDO::FETCH_ASSOC);
}
//获取多行数据
public function fetchAll($sql){
$PDOStatement = $this->query($sql);
return $PDOStatement->fetchAll(PDO::FETCH_ASSOC);
}
//获取记录行
public function rowCount($sql){
try {
$PDOStatement = $this->pdo->query($sql);
return $PDOStatement->rowCount();
} catch (PDOException $e) {
$this->showErr($e);
}
}
//显示错误的方法
private function showErr($e){
echo '<h2>SQL语句有问题</h2>';
echo '<br>错误编号'.$e->getCode();
echo '<br>错误行号'.$e->getLine();
echo '<br>错误文件'.$e->getFile();
echo '<br>错误信息'.$e->getMessage();
die();
}
// 析构方法销毁对象
public function __destruct(){
$this->pdo = null;
}
}