作用:主要作用通过构建PDO对象与数据库进行交互
代码解析
属性:
protected $config = [
//数据类型
'type'=>'',
//服务器地址
'hostname'=>'',
//端口号
'hostport'=>'',
//数据库名
'dbname'=>'',
//用户名
'username'=>'',
//密码
'password'=>''
];
//PDO连接ID 支持多个数据库连接
protected $links = [];
//连接参数
protected $params = [
PDO::ATTR_CASE => PDO::ATTR_CASE_NATURAL,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_ORACLES_NULLS => PDO::NULL_NATURAL,
PDO::ATTR_STRINGIFY_FETCHES => false,
PDO::ATTR_EMULATE_PREPARES =>false
]
protected $fetchType = PDO::FETCH_ASSOC;
初始化:
public function __construct(array $config=[]){
if(!empty($config)){
$this->config = array_merge($this->config,$config);
}
}
连接数据库:
public function connection(array $config=[],$linknum=0,$autoconnection=false){
if(!isset($this->links[$linknum])){
if (!$config) {
$config = $this->config;
}else{
$config = array_merge($this->config,$config);
}
if(isset($config['params'] && is_array($config['params'])){
$params = $config['params'] + $this->params;
}else{
$params = $this->params;
}
if (isset($config['result_type'])){
$this->fetchType = $config['result_type'];
}
if(!isset($config['dsn'])){
$config['dsn'] = $this->parseDsn($config);
}
try{
$this->links[$linknum] = new PDO($config['dsn'],$config['username'],$config['password'],$params);
}catch(PDOException $e){
throw $e;
}
}
return $this->links[$linknum];
}
protected function parseDsn(array $config){
if(!empty($config['socket'])){
$dsn = 'mysql:unix_socket='.$config['socket'];
}elseif (!empty($config['hostport'])) {
$dsn = 'mysql:host='.$config['hostname'].';port='.$config['hostport'];
}else{
$dsn = 'mysql:host='.$config['hostname'];
}
$dsn.= ';dbname='.$config['database'];
if (!empty($config['charset'])) {
$dsn.= ';charset='.$config['charset'];
}
return $dsn;
}
?>