我如何存储PDO对象

时间:2016-02-17 16:29:34

标签: php mysql pdo

现在每次我需要运行查询时,我都会调用一个名为connection()的函数来创建一个新的PDO对象。

function connection(){
    $host   = 'localhost';
    $user   = 'user';
    $pass   = 'password';
    $dbName = 'db_name';
    new PDO("mysql:host=$host; dbname=$dbName", $user, $pass);
}

$db = connection();
$query = 'SELECT ...';
$stmt  = $db->prepare($query);
$stmt->execute();

问题是网站只需1秒钟即可创建此对象,而且,如果我需要运行4个查询,页面将在4秒内加载。那么,有什么办法可以存储这个PDO对象来优化性能吗?

我在多个文件中使用此功能,所以我需要它。

3 个答案:

答案 0 :(得分:2)

如果您创建一个包含在页面顶部的config.php文件,该怎么办?您只需要创建一次对象,页面上的所有查询都可以引用同一个对象:

function connection(){
    $host   = 'localhost';
    $user   = 'user';
    $pass   = 'password';
    $dbName = 'db_name';
    new PDO("mysql:host=$host; dbname=$dbName", $user, $pass);
}

$db = connection();

$query = 'Statement #1';
$stmt  = $db->prepare($query);
$stmt->execute();

$query = 'Statement #2';
$stmt  = $db->prepare($query);
$stmt->execute();

$query = 'Statement #3';
$stmt  = $db->prepare($query);
$stmt->execute();

$query = 'Statement #4';
$stmt  = $db->prepare($query);
$stmt->execute();

答案 1 :(得分:1)

这样的事可能

function connection(){
    static $CONN;
    if (!$CONN) {
        $host   = 'localhost';
        $user   = 'user';
        $pass   = 'password';
        $dbName = 'db_name';
        $CONN = new PDO("mysql:host=$host; dbname=$dbName", $user, $pass);
    }
    return $CONN;
}

这可能会做你想要的,没有太多额外的改变。

答案 2 :(得分:0)

有几个人提到过static和Singleton模式。这就是代码的样子,一次只保留一个PDO对象的实例:

class DB{

     private static $_instance;
     private $_pdo;

     public static function getInstance(){
         if(self::$_instance === NULL) {
            $dsn = 'mysql:dbname=dbname;host=host';
            $user = 'user';
            $password = 'password';
            // call constructor and assign instance
            self::$_instance = new self($dsn, $user, $password);
        }

        return self::$_instance;
    }

    /**
     * Creates new DB wrapping a PDO instance
     *
     * Constructor is private because this class can't be instantiated.
     *
     */
    private function __construct($dsn, $user, $password){
        try {
            $this->_pdo = new PDO($dsn, $user, $password);
        } catch (PDOException $e) {
            echo 'Connection failed: ' . $e->getMessage();
        }
     }

    /**
     * Singletons may not be cloned
     */
    private function __clone() {}


    /**
     * Delegate every method call to PDO instance
     *
     * @param  String $method
     * @param  Array  $args
     * @return Mixed
     */
    public function __call($method, $args) {
        return call_user_func_array(array($this->_pdo, $method), $args);
    }
}

// To instantiate:
$db = DB::getInstance();