仅在需要时自动连接到 PDO
我有一段代码,根据请求的 URL,将包含其他十四个文件之一.这 14 个文件中的一些需要连接到三个不同数据库之一,并且可以随时添加其他文件.
I have a section of code that depending on the URL requested, will include one of fourteen other files. Some of these fourteen files require a connection to one of three different databases, and additional files can be added at anytime.
我不想默认打开所有三个数据库的 PDO 连接,因为它浪费资源并且会减慢执行时间.所以我的想法是将所有 SQL 查询包装在一个函数中.第一次在未打开的 PDO 连接上执行查询时,try {} 错误处理程序可以捕获它,找出问题所在(在这种情况下连接不存在),然后打开连接并重新执行询问.这样,数据库只在需要时才连接 - 只要连接字符串(主机、数据库、用户名、密码)都预先定义,我看不出它有任何问题.
I don't want to open PDO connections by default to all three database as its a waste of resources and will slow the execution time down. So my thought is to wrap all SQL queries within a function. The first time that a query is executed on a non-open PDO connection, the try {} error handler can catch it, find out what the problem was (in this case connection doesnt exist), then open the connection and re-execute the query. That way, the database is only being connected to as and when needed - as long as the connection string (host, database, username, password) are all defined in advance, I can't see any problem in it working.
但是,我需要继续推进,并且在大约 7 天内无法访问开发箱,所以任何人都可以看出这种情况有什么问题吗?另外,如果没有打开连接,谁能告诉我 handler->errorInfo() 将返回的错误消息?
However, I need to push on with this, and don't have access to the dev box for about 7 days, so can anyone see any problem with that scenario? Also, can anyone give me the error message that handler->errorInfo() will return if the connection isn't opened?
推荐答案
这是正确的想法,但不是它的最佳实现.
This is the right idea, but not the best implementation of it.
包装 SQL 操作很好.但是你为什么不这样做呢:
Wrapping the SQL operations is good. But why don't you do it this way:
class Wrapper {
private static $db;
public static function someQuery() {
$db = self::getDatabase();
// now go on to execute the query
}
private static function getDatabase() {
if (self::$db === null) {
self::$db = // connect here
}
return self::$db;
}
}
这有很多优点:
- 允许您在逻辑上将 SQL 操作分组为一个(或多个!)类
- 如果不需要,不连接到数据库
- 不依赖(脆弱的)错误检查来正常运行
在您的特定情况下,您可能应该使用 3 个单独的 Wrapper
类.将所有内容都放在一个类中是可行的(三个不同的 $db
变量),但可能比它的价值更令人困惑.
In your specific case, you should probably go with 3 separate Wrapper
classes. Putting everything into one class is doable (three different $db
variables) but probably more confusing than it's worth.
相关文章