1 回答
TA贡献1887条经验 获得超5个赞
经过一番深思熟虑,我想我已经解决了。
我使用容器创建了 PDO 实例
$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);
});
然后将存储库更改为使用构造函数中的 App,然后使用容器获取 PDO 实例
/**
* @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');
}
将此留在这里,以防其他人遇到问题,尽管有更好的方法可以做到这一点,或者我目前的方法可以改进,我将不胜感激的反馈
- 1 回答
- 0 关注
- 94 浏览
添加回答
举报