我在这里有点困惑,我正在努力让自己陷入困境并且有点挣扎。我一直在使用Aura SQL(php)并且已经实现了我所需要的,但是,有必要连接到多个数据库以更新我已经传递的一些遗留代码。
class Core {
public $pdo;
private static $instance;
private function __construct() {
$this->pdo = new ExtendedPdo(
'mysql:host=localhost;charset=utf8;dbname=db',
'user',
'pass'
);
$this->pdo->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, 'SET NAMES utf8');
}
public static function getInstance() {
if (!isset(self::$instance)) {
$object = __CLASS__;
self::$instance = new $object;
}
return self::$instance;
}
}
我试图通过构造函数传递值来修改,但是,它似乎被忽略了,例如:
private function __construct($db_name) {
if !empty($db_name)) { $this->db = $db_name; } else { $this->db = 'default_db'; }
$this->pdo = new ExtendedPdo(
'mysql:host=localhost;charset=utf8;dbname='.$this->db.'',
....
通常你会使用getInstance();但我一直在尝试实例化一个新对象来访问其他数据库。
感谢您的任何建议。
答案 0 :(得分:1)
请查看ConnectionLocator,您可以通过该{{3}}创建默认连接,以及其他连接。从自述文件中获取代码片段。
<?php
use Aura\Sql\ConnectionLocator;
use Aura\Sql\ExtendedPdo;
// default connection
$default = function () {
return new ExtendedPdo(
'mysql:host=default.db.localhost;dbname=database',
'username',
'password'
);
};
// read connections
$read = array(
'slave1' => function () {
return new ExtendedPdo(
'mysql:host=slave1.db.localhost;dbname=database',
'username',
'password'
);
},
'slave2' => function () {
return new ExtendedPdo(
'mysql:host=slave2.db.localhost;dbname=database',
'username',
'password'
);
},
'slave3' => function () {
return new ExtendedPdo(
'mysql:host=slave3.db.localhost;dbname=database',
'username',
'password'
);
},
);
// write connection
$write = array(
'master' => function () {
return new ExtendedPdo(
'mysql:host=master.db.localhost;dbname=database',
'username',
'password'
);
},
);
// configure locator at construction time
$connections = new ConnectionLocator($default, $read, $write);
$default_connection = $connections->getDefault();
$read_slave1_connection = $connections->getRead('slave1');
$read_any_connection = $connections->getRead();
$write_connection = $connections->getWrite();