1 回答

TA貢獻(xiàn)1887條經(jīng)驗(yàn) 獲得超5個(gè)贊
經(jīng)過一番深思熟慮,我想我已經(jīng)解決了。
我使用容器創(chuàng)建了 PDO 實(shí)例
$container = $app->getContainer();
$container->set('db', function(ContainerInterface $c) {
$config = $c->get(Configuration::class);
$host = $config->getString('db.host');
$dbname = $config->getString('db.database');
$username = $config->getString('db.username');
$password = $config->getString('db.password');
$dsn = "mysql:host=$host;dbname=$dbname;";
return new PDO($dsn, $username, $password);
});
$container->set('db_readonly', function(ContainerInterface $c) {
$config = $c->get(Configuration::class);
$host = $config->getString('db_readonly.host');
$dbname = $config->getString('db_readonly.database');
$username = $config->getString('db_readonly.username');
$password = $config->getString('db_readonly.password');
$dsn = "mysql:host=$host;dbname=$dbname;";
return new PDO($dsn, $username, $password);
});
然后將存儲(chǔ)庫更改為使用構(gòu)造函數(shù)中的 App,然后使用容器獲取 PDO 實(shí)例
/**
* @var PDO The database
*/
private $db;
/**
* @var PDO The readonly database
*/
private $readonly_db;
/**
* Constructor.
*
* @param App $app The database db
*/
public function __construct(App $app)
{
$container = $app->getContainer();
$this->db = $container->get('db');
$this->readonly_db = $container->get('db_readonly');
}
將此留在這里,以防其他人遇到問題,盡管有更好的方法可以做到這一點(diǎn),或者我目前的方法可以改進(jìn),我將不勝感激的反饋
- 1 回答
- 0 關(guān)注
- 119 瀏覽
添加回答
舉報(bào)