使用单例模式的PDO连接类

时间:2012-10-22 07:52:58

标签: php mysql pdo singleton

<?php

//db connection class using singleton pattern
class dbConn {
    //variable to hold connection object.
    protected static $db;

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

        try { // assign PDO object to db variable
            self::$db = new PDO('mysql:host=localhost;dbname=cricket', 'root', '');
            setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch (PDOException $e) { //Output error – would normally log this to error file rather than output to user.
            echo "Connection Error: " . $e->getMessage();
        }
    }

    // get connection function. Static method – accessible without instantiation
    public static function getConnection()
    {
        //Guarantees single instance, if no connection object exists then create one.
        if (!self::$db) { //new connection object.
            new dbConn();
        }
    //return connection.
    return self::$db;
    }
}
//end class

?>

如果我在索引中调用此参数,请检查此错误

    $sql = "select * from user";
    $q = dbConn::getConnection()->query($sql);

   $result =  $q->fetch();
    print_r($result);
}

教程链接:http://weebtutorials.com/2012/03/pdo-connection-class-using-singleton-pattern/

1 个答案:

答案 0 :(得分:6)

您的代码有几个问题(除了PHP中单例模式的有用性):

单例的想法是实例由私有静态变量引用,在代码中不是这种情况,您引用PDO对象的实例。您的代码的 true 单例版本必须如下所示:

class TrueSingleton
{
    private static $_instance;
    private $_pdo;

    private function __construct()
    {//private constructor:
        $this->_pdo = new PDO();//<-- connect here
        //You set attributes like so:
        $this->_pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        //not setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);<-- PHP can't know which setAttribute method to call on what object
    }
    public static function getConnection()
    {
        if (self::$_instance === null)//don't check connection, check instance
        {
            self::$_instance = new TrueSingleton();
        }
        return self::$_instance;
    }
    //to TRULY ensure there is only 1 instance, you'll have to disable object cloning
    public function __clone()
    {
        return false;
    }
    public function __wakeup()
    {
        return false;
    }
}

其余部分非常基础,除了每当您需要查询数据库时,您必须在成员函数中使用$this->_pdo->query()

相关问题