我可以创建一个实例PDO
并成功注入它。我PDO::class
直接定义并在构造函数中注入了__construct(PDO $pdo)
. 我需要类似的东西PDO1::class
并PDO2::class
像下面这样注入它:__construct(PDO1 $pdo1, PDO2 $pdo2)
但这显然行不通。只有一个PDO
类,我需要做的是具有不同数据库凭据的 2 个实例。
最好的方法是什么?
我通过这样的 PDO 设置了一个数据库定义,它可以工作:
文件:dependencies.php
use DI\ContainerBuilder;
use Psr\Container\ContainerInterface;
return function (ContainerBuilder $containerBuilder) {
$containerBuilder->addDefinitions([
PDO::class => function (ContainerInterface $c) {
$dbSettings = $c->get('settings')['db1'];
$dsn = 'mysql:host=' . $dbSettings['host'] . ';dbname=' . $dbSettings['dbname'];
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
return new PDO($dsn, $dbSettings['user'], $dbSettings['pass'], $options);
},
]);
};
文件:index.php
...
// Set up dependencies
$dependencies = require __DIR__ . '/../app/dependencies.php';
$dependencies($containerBuilder);
// Build PHP-DI Container instance
$container = $containerBuilder->build();
// Set container to create App with on AppFactory
AppFactory::setContainer($container);
// Instantiate the app
$app = AppFactory::create();
...
文件SomeRepository.php
use PDO;
class SomeRepository{
protected $pdo;
public function __construct(PDO $pdo) {
$this->pdo = $pdo;
}
}
我在这篇文章中看到过这样的事情:
return function (ContainerBuilder $containerBuilder) {
$containerBuilder->addDefinitions([
'db1' => function (ContainerInterface $c) {
$db1Settings = $c->get('settings')['db1'];
$dsn = 'mysql:host=' . $db1Settings['host'] . ';dbname=' . $db1Settings['dbname'];
$options = [ ... ];
return new PDO($dsn, $db1Settings['user'], $db1Settings['pass'],$options);
},
'db2' => function (ContainerInterface $c) {
$db2Settings = $c->get('settings')['db2'];
$dsn = 'mysql:host=' . $db2Settings['host'] . ';dbname=' . $db2Settings['dbname'];
$options = [ ... ];
return new PDO($dsn, $db2Settings['user'], $db2Settings['pass'],$options);
},
]);
};
但这是最好的方法吗?以及如何在无需注入整个容器的情况下访问存储库类中的连接?