问题描述
我有一段代码,根据请求的URL,将包括十四个其他文件之一。这些十四个文件中的一些需要连接到三个不同的数据库之一,并且可以随时添加其他文件。
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操作逻辑分组到一个(或多个!)类中
- 不连接到数据库if
在您的具体情况下,您应该可以使用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.
这篇关于仅在需要时自动连接到PDO的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!