add singleton pattern in Db service of getPdo() function

This commit is contained in:
Jack 2015-01-23 16:19:03 +08:00
parent e40848e98b
commit 84611b8547
4 changed files with 19 additions and 14 deletions

View File

@ -11,7 +11,7 @@ class Dbh
function __construct($db = NULL)
{
if($db == NULL)
$this->db = new PDO();
$this->db = PDO::getInstance();
else
$this->db = $db;
}

View File

@ -3,26 +3,31 @@ namespace Westdc\Db;
use Zend\Config\Config as Zend_Config;
class Pdo extends \PDO
class Pdo
{
private $debug = 0; //调试模式
private static $_instance = NULL;
private $config_local_path = "config/autoload/local.php";
function __construct($DSN = NULL)
private function __construct($DSN = NULL)
{
if (!empty($DSN)) {
parent::__construct($DSN);
} else {
$config_local = new Zend_Config(include $this->config_local_path);
}
public static function getInstance()
{
if (self::$_instance === null) {
$config_local = new Zend_Config(include "config/autoload/local.php");
$dsn = "pgsql:host={$config_local->db->hostname};"
. "port={$config_local->db->port};"
. "dbname={$config_local->db->database};"
. "user={$config_local->db->username};"
. "password={$config_local->db->password}";
parent::__construct($dsn);
self::$_instance = new \PDO($dsn);
}
return self::$_instance;
}
}

View File

@ -2,7 +2,7 @@
namespace Westdc\Member;
use Westdc\Helpers\Config;
use Westdc\Db\PDO as Db;
use Westdc\Db\Pdo as Db;
class Cookie
{
@ -27,7 +27,7 @@ class Cookie
function __construct()
{
$this->db = new Db();
$this->db = Db::getInstance();
$this->config = Config::get();
if(!empty($_COOKIE['scr']))

View File

@ -21,7 +21,7 @@ class Db {
public function getPdo()
{
return new WestdcDb\Pdo;
return WestdcDb\Pdo::getInstance();
}
public function getDbh()