我刚刚开始使用Slim 4(也是整个Slim的全新内容),在阅读并阅读了一些文章之后,我设法获得了一个具有PDO连接到DB的骨架应用程序设置。
我现在正在寻找第二个PDO实例,以便可以根据请求使用第二个数据库,尽管我正在努力了解如何执行此操作。
我目前的设置是:
设置.php
$settings['db'] = [
'driver' => 'mysql',
'host' => 'database',
'username' => 'root',
'database' => 'demo',
'password' => 'password',
'flags' => [
// Turn off persistent connections
PDO::ATTR_PERSISTENT => false,
// Enable exceptions
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
// Emulate prepared statements
PDO::ATTR_EMULATE_PREPARES => true,
// Set default fetch mode to array
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
],
];
容器.php
return [
Configuration::class => function () {
return new Configuration(require __DIR__ . '/settings.php');
},
App::class => function (ContainerInterface $container) {
AppFactory::setContainer($container);
$app = AppFactory::create();
return $app;
},
PDO::class => function (ContainerInterface $container) {
$config = $container->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);
},
];
存储库中的用法示例
class UserReaderRepository
{
/**
* @var PDO The database connection
*/
private $connection;
/**
* Constructor.
*
* @param PDO $connection The database connection
*/
public function __construct(PDO $connection)
{
$this->connection = $connection;
}
慕工程0101907