尝试使用PDO和单例模式创建数据库连接

时间:2014-01-28 21:06:05

标签: php design-patterns pdo singleton

我一直在尝试使用PDO和singleton创建数据库连接。我想我已经完成了但是我不确定我是否使用了正确的单例模式。

我也不确定我是否正确使用__clone()__wakeup()方法。我没有测试它们的知识。

有人可以告诉我,如果我的方法是在正确的道路上,并且我是否正确使用单身模式?我很擅长设计模式。

这是我的代码:

<?php

require_once 'config.php';

class dbConn{

// Variable to store connection object.
protected static $db;

// Assign variables from config.php.
private $host   = DB_HOST;
private $dbuser = DB_USER;
private $dbpass = DB_PASS;
private $dbname = DB_NAME;

// Private construct - class cannot be instatiated externally.
private function __construct() {

    try {
        // Try to create PDO object to the $db variable.
        $pre = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;
        self::$db = new PDO($pre, $this->dbuser, $this->dbpass);
        self::$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
    }
    // If not able to connect to database.
    catch (PDOException $e) {
        echo "Could not connect: " . $e->getMessage();
    } 
}

// Get connection function.
public static function getConnection() {

// Only if no connection object exists it creates one, because we only want one instance.
    if (!self::$db) {
// New connection object.
        new dbConn();
}
    return self::$db;
}

public function __clone() {
        return false;
    }

public function __wakeup(){
        return false;
    }
}

$db = dbConn::getConnection()

?>

2 个答案:

答案 0 :(得分:1)

这不是单例模式:php中的单例是一个将自身的唯一实例存储在静态变量中的类。

恕我直言是不使用单身人士课程的好习惯,静态分类可以做同样的事情。

对于您想要获得的内容,您可以看到依赖注意或

创建这样的东西:

class Database extends PDO {
   private $engine = 'mysql';
   private $host = 'localhost';
   private $database = 'Crumbs';
   private $user = 'root';
   private $pass = 'adminuser';

   public function __construct()
   {
      $dns = $this->engine.':dbname='.$this->database.";host=".$this->host;
      parent::__construct( $dns, $this->user, $this->pass );
   } 
}

然后使用:

$db = new Database();

答案 1 :(得分:1)

仅供您知道:

依赖性iniection是一种模式:

class Class {
   private $dependency;
   public function __construct($dep) {
      $this->$dependency = $dep;
   }

   function use_dependency( ... ) {
      $dep = $this->$dependency;
      ...
      $dep->action();
      ...
    }
}

$dep = new Dependency();
$c = new Class( $dep );

单身模式如下:

class Singleton
{
    protected static $instance = null;
    protected function __construct()
    {
        //Thou shalt not construct that which is unconstructable!
    }
    protected function __clone()
    {
        //Me not like clones! Me smash clones!
    }

    public static function getInstance()
    {
        if (!isset(static::$instance)) {
            static::$instance = new static;
        }
        return static::$instance;
    }
}

但我重申这是不好的做法。

还要注意反序列化后调用__wakeup(参见http://www.php.net/manual/en/language.oop5.magic.php