問題描述
我有一段代碼,根據請求的 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.
這篇關于僅在需要時自動連接到 PDO的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!