是否可以将 PDO 连接保存到$GLOBALS并在以后使用它来确保创建一次连接?



我只想确保PDO连接创建一次,以便对脚本进行一些优化。

下面的代码可以变得更加漂亮和易于维护,但在这里我只想让它尽可能简单。(即使用类和构造函数(

此代码是否确保 PDO 连接创建一次?换句话说,被调用的方法应该能够检索已经在索引中创建的连接.php并使用它。

它可能会更优化(提高性能(吗?

更新: 我不是在谈论持久连接。

索引.php

require 'file.php';
$GLOBALS['db_connection'] = new PDO("sqlite:db.sqlite");
if(request == 'create_user')
user::create_user();
// ...
else
exit();

文件.php

class user{
public static function create_user(){
$conn = $GLOBALS['db_connection']; // should not attempt to reconnect because a PDO connection is already made in index.php
$stmt = $conn->prepare("INSERT INTO table1 ...");
// ...
functions::do_sth(); // again should not attempt to reconnect because a PDO connection is already made in index.php
// ...
exit();
}
}
class functions{
public static function do_sth(){
$conn = $GLOBALS['db_connection']; // should not attempt to reconnect because a PDO connection is already made in index.php
// ...
}
}

代码的替代方法是使用单例模式。

在软件工程中,单例模式是一种软件设计模式,它将类的实例化限制为一个"单个"实例。当只需要一个对象来协调整个系统中的操作时,这很有用。

例:

class Connection {
private static $instance;
public static function make($config){
try {
if(self::$instance === NULL) {
self::$instance = 
new PDO ("mysql:host=" . $config['host'] . ";
dbname=" . $config['name'],$config['username'],$config['password'],$config['options']
);
}
return self::$instance;
} catch (PDOException $e) {
die("Database connection error: " . $e->getMessage());
}
}
}
// use 
$dbConnection = Connection::make($config['database']);

最新更新