在有人说这个问题已经得到回答之前,请注意,虽然在容器中定义多个 pdo 连接已经解释了 here 和 here,但我的问题更多地是关于构建的最佳方法来自从主数据库获取的 json 对象的动态 pdo 连接。
我使用以下 Database 类创建我需要的任何数据库连接,无论何时何地都需要它们。
class Database {
private static $dbs = array();
# we declare as static so the state is kept between function calls to connect
# this allows to connect just once to the database and then just return the connection
# on future function calls
private static $conn = null;
# now since we dont want to reinstiate the class anytime we need it, lets also set the constructor to private
private function __construct(){}
# get the database connection
public static function connect( $name, $opt, $struct, $key = null ) {
if( empty( self::$dbs[$name] ) ) {
try {
$struct['username'] = ( null === $key ) ? $struct['username'] : Security::XORDecrypt( $struct['username'], $key );
$struct['password'] = ( null === $key ) ? $struct['password'] : Security::XORDecrypt( $struct['password'], $key );
switch( $struct['type'] ) {
case 'sqlsrv': # MSSQL
self::$conn = new PDO( "sqlsrv:server=" . $struct['hostname'] . ";" . "ConnectionPooling=1;" . "database=" . $struct['database'], $struct['username'], $struct['password'], array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::SQLSRV_ATTR_QUERY_TIMEOUT => intval( $struct['timeout'], 10 ) ) );
break;
}
self::$dbs[$name] = self::$conn;
return self::$conn;
}
catch( PDOException $ex ) {
if( $opt == 1 )
echo "<p class='bg-danger'>Connection error: " . $ex->getMessage() . "</p>";
else
die( json_encode( array( 'outcome' => false, 'message' => 'Unable to connect' ) ) );
}
}
return self::$dbs[$name];
}
public static function disconnect( $name ) {
if( self::$dbs[$name] != NULL ) {
self::$dbs[$name] = NULL;
}
}
}
每当我需要连接到数据库时,它都是这样完成的
$pre = '_' . $app_id; $$pre = '';
$conn = Database::connect( $pre, $env['options']['env'], $apps['db_conns'][$app_id], $i_key );
在上面:
$app_id
:存储正在请求数据的应用程序实例的 id
$env['options']['env']
:存储我们正在运行的环境、开发/生产等。
$apps['db_conns'][$app_id]
:是一个多关联数组,用于存储每个数据库的数据库连接详细信息(用户名/密码/端口)等
$i_key
:存储用于加密连接详细信息的哈希值(从另一个进程获取)
然后将 $conn
传递给执行请求的数据库操作的类。当不再需要连接时,我使用
Database::disconnect( $pre );