php 用于PHP PDO连接的类 - 单例实现。实例方法返回具有指定连接的新PDO连接
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php 用于PHP PDO连接的类 - 单例实现。实例方法返回具有指定连接的新PDO连接相关的知识,希望对你有一定的参考价值。
<?php
namespace ACompany\AnAppName\Dao\PdoImpl;
/**
* PDOConnection is a singleton implementation.
* getConnection() returning an instance of PDO connection.
*
* <code>
* Example usage:
*
* $pdo = PDOConnection::instance();
* $conn = $pdo->getConnection( 'dsn', 'username', 'password' );
*
* $results = $conn->query("SELECT * FROM Table");
*
* </code>
*
* @author rmurray
*/
class PDOConnection {
/**
* singleton instance
*
* @var PDOConnection
*/
protected static $_instance = null;
/**
* Returns singleton instance of PDOConnection
*
* @return PDOConnection
*/
public static function instance() {
if ( !isset( self::$_instance ) ) {
self::$_instance = new PDOConnection();
}
return self::$_instance;
}
/**
* Hide constructor, protected so only subclasses and self can use
*/
protected function __construct() {}
function __destruct(){}
/**
* Return a PDO connection using the dsn and credentials provided
*
* @param string $dsn The DSN to the database
* @param string $username Database username
* @param string $password Database password
* @return PDO connection to the database
* @throws PDOException
* @throws Exception
*/
public function getConnection($dsn, $username, $password) {
$conn = null;
try {
$conn = new \PDO($dsn, $username, $password);
//Set common attributes
$conn->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
return $conn;
} catch (PDOException $e) {
//TODO: flag to disable errors?
throw $e;
}
catch(Exception $e) {
//TODO: flag to disable errors?
throw $e;
}
}
/** PHP seems to need these stubbed to ensure true singleton **/
public function __clone()
{
return false;
}
public function __wakeup()
{
return false;
}
}
以上是关于php 用于PHP PDO连接的类 - 单例实现。实例方法返回具有指定连接的新PDO连接的主要内容,如果未能解决你的问题,请参考以下文章
PHP单例模式
single单例模式
PHP实现的pdo连接数据库并插入数据功能简单示例
使用 PHP PDO 设计数据库抽象类
PHP pdo 实例作为私有静态属性
PHP中的PDO函数库