問題描述
我正在考慮在我未來的所有 web 應用程序中使用 PDO.目前(使用到目前為止我從 SO 中學到的知識),我在我的站點中處理數據庫連接的是一個像這樣的 Singleton 類:
I'm thinking of using PDO in all of my future webapp. Currently (using what I've learned from SO so far), what I have in my site to handle database connection is a Singleton class like this :
class DB {
private static $instance = NULL;
private static $dsn = "mysql:host=localhost;dbname=mydatabase;";
private static $db_user = 'root';
private static $db_pass = '0O0ooIl1';
private function __construct()
{
}
private function __clone()
{
}
public static function getInstance() {
if (!self::$instance)
{
self::$instance = new PDO(self::$dsn, self::$db_user, self::$db_pass);
self::$instance-> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
return self::$instance;
}
}
和另一個文件 (functions.php) 與內容特定的函數看起來完全一樣:
and another file (functions.php) with content-specific functions looking exactly like this one :
function get_recent_activities ()
{
try
{
$db = DB::getInstance();
// --prepare and execute query here, fetch the result--
return $my_list_of_recent_activities;
}
catch (PDOException $e)
{
return "some fail-messages";
}
}
...
意味著我必須在所有函數中重復 try .. catch
部分.
meaning that I have to repeat the try .. catch
part in all of the functions.
我的問題是:
- 我應該如何提高效率?(例如,不必在所有函數中重復
try..catch
,但仍然能夠在每個函數上返回不同的失敗消息") - 這已經是一個好習慣了嗎?我還是 PDO 和 OOP 的新手(還有很多東西要學習),所以(截至目前),我真的看不出有什么缺點或可以改進的地方.
- How should I make that more efficient ? (eg. not having to repeat
try..catch
in all functions, and yet still able to return different "fail-message" on each one) - Is this already a good practice ? I'm still new at PDO and OOP (still a lot more to learn), so (as of now), I can't really see any disadvantages or things that can be improved in there.
如果這看起來不清楚或太長,我很抱歉.提前致謝.
I'm sorry if that seems unclear or too long. Thanks in advance.
推薦答案
你的實現很好,而且在大多數情況下都能很好地工作.
Your implementation is just fine, and it'll work perfectly well for most purposes.
沒有必要將每個查詢都放在 try/catch 塊中,事實上,在大多數情況下,您實際上并不想這樣做.這樣做的原因是,如果查詢生成異常,則是語法錯誤或數據庫問題等致命問題的結果,而這些不是您在執行每個查詢時都應該考慮的問題.
It's not necessary to put every query inside a try/catch block, and in fact in most cases you actually don't want to. The reason for this is that if a query generates an exception, it's the result of a fatal problem like a syntax error or a database issue, and those are not issues that you should be accounting for with every query that you do.
例如:
try {
$rs = $db->prepare('SELECT * FROM foo');
$rs->execute();
$foo = $rs->fetchAll();
} catch (Exception $e) {
die("Oh noes! There's an error in the query!");
}
這里的查詢要么正常工作,要么根本不工作.它根本不起作用的情況在生產系統上不應該有規律地發生,所以它們不是您應該在這里檢查的條件.這樣做實際上適得其反,因為您的用戶會收到永遠不會改變的錯誤,而您不會收到提醒您問題的異常消息.
The query here will either work properly or not work at all. The circumstances where it wouldn't work at all should not ever occur with any regularity on a production system, so they're not conditions that you should check for here. Doing so is actually counterproductive, because your users get an error that will never change, and you don't get an exception message that would alert you to the problem.
相反,只需這樣寫:
$rs = $db->prepare('SELECT * FROM foo');
$rs->execute();
$foo = $rs->fetchAll();
一般來說,您唯一需要捕獲和處理查詢異常的時間是在查詢失敗時您想執行其他操作的時候.例如:
In general, the only time that you'll want to catch and handle a query exception is when you want to do something else if the query fails. For example:
// We're handling a file upload here.
try {
$rs = $db->prepare('INSERT INTO files (fileID, filename) VALUES (?, ?)');
$rs->execute(array(1234, '/var/tmp/file1234.txt'));
} catch (Exception $e) {
unlink('/var/tmp/file1234.txt');
throw $e;
}
您需要編寫一個簡單的異常處理程序,用于記錄或通知您生產環境中發生的數據庫錯誤,并向您的用戶顯示友好的錯誤消息而不是異常跟蹤.請參閱 http://www.php.net/set-exception-handler 了解有關怎么做.
You'll want to write a simple exception handler that logs or notifies you of database errors that occur in your production environment and displays a friendly error message to your users instead of the exception trace. See http://www.php.net/set-exception-handler for information on how to do that.
這篇關于函數中的 PDO try-catch 用法的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!