如何在 slim 4 中设置和注入多个 PDO 数据库连接?
问题描述
我可以创建一个 PDO
的实例并成功注入它.我直接定义了 PDO::class
并用 __construct(PDO $pdo)
将它注入到构造函数中.我需要像 PDO1::class
和 PDO2::class
之类的东西来注入它,如下所示:__construct(PDO1 $pdo1, PDO2 $pdo2)
但这显然行不通.只有一个 PDO
类,我需要做的是它的 2 个具有不同数据库凭据的实例.
最好的方法是什么?
I could make an instance of PDO
and inject it successfully. I defined the PDO::class
directly and injected it in the constructor with __construct(PDO $pdo)
. I would need something like PDO1::class
and PDO2::class
to inject it like follows: __construct(PDO1 $pdo1, PDO2 $pdo2)
but that obviously doesn't work. There is only one PDO
class and what I need to do is 2 instances of it with different database credentials.
What is the best way to do it?
我像这样通过 PDO 设置了一个数据库定义并且它可以工作:
I set up one definition of a database via PDO like this and it works:
文件:dependencies.php
文件:index.php
文件 SomeRepository.php
我在这篇文章中看到过类似的内容:
I've seen something like this in this article:
但这是最好的方法吗?以及如何在不必注入整个容器的情况下访问存储库类中的连接?
But is it the best way to do it? And how can I access the connections in a repository class without having to inject the whole container?
推荐答案
您有多种选择:
- 扩展 PDO
- 自动装配的对象
1.扩展 PDO
容器定义:
使用
2.自动装配对象
参见 Matthieu Napoli 的回答:https://stackoverflow.com/a/57758106/1461181
See Matthieu Napoli's answer: https://stackoverflow.com/a/57758106/1461181
这篇关于如何在 slim 4 中设置和注入多个 PDO 数据库连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!