問題描述
我正在考慮在我未來的所有 web 應(yīng)用程序中使用 PDO.目前(使用到目前為止我從 SO 中學(xué)到的知識(shí)),我在我的站點(diǎn)中處理數(shù)據(jù)庫連接的是一個(gè)像這樣的 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;
}
}
和另一個(gè)文件 (functions.php) 與內(nèi)容特定的函數(shù)看起來完全一樣:
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";
}
}
...
意味著我必須在所有函數(shù)中重復(fù) try .. catch
部分.
meaning that I have to repeat the try .. catch
part in all of the functions.
我的問題是:
- 我應(yīng)該如何提高效率?(例如,不必在所有函數(shù)中重復(fù)
try..catch
,但仍然能夠在每個(gè)函數(shù)上返回不同的失敗消息") - 這已經(jīng)是一個(gè)好習(xí)慣了嗎?我還是 PDO 和 OOP 的新手(還有很多東西要學(xué)習(xí)),所以(截至目前),我真的看不出有什么缺點(diǎn)或可以改進(jìn)的地方.
- 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.
推薦答案
你的實(shí)現(xiàn)很好,而且在大多數(shù)情況下都能很好地工作.
Your implementation is just fine, and it'll work perfectly well for most purposes.
沒有必要將每個(gè)查詢都放在 try/catch 塊中,事實(shí)上,在大多數(shù)情況下,您實(shí)際上并不想這樣做.這樣做的原因是,如果查詢生成異常,則是語法錯(cuò)誤或數(shù)據(jù)庫問題等致命問題的結(jié)果,而這些不是您在執(zhí)行每個(gè)查詢時(shí)都應(yīng)該考慮的問題.
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!");
}
這里的查詢要么正常工作,要么根本不工作.它根本不起作用的情況在生產(chǎn)系統(tǒng)上不應(yīng)該有規(guī)律地發(fā)生,所以它們不是您應(yīng)該在這里檢查的條件.這樣做實(shí)際上適得其反,因?yàn)槟挠脩魰?huì)收到永遠(yuǎn)不會(huì)改變的錯(cuò)誤,而您不會(huì)收到提醒您問題的異常消息.
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();
一般來說,您唯一需要捕獲和處理查詢異常的時(shí)間是在查詢失敗時(shí)您想執(zhí)行其他操作的時(shí)候.例如:
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;
}
您需要編寫一個(gè)簡單的異常處理程序,用于記錄或通知您生產(chǎn)環(huán)境中發(fā)生的數(shù)據(jù)庫錯(cuò)誤,并向您的用戶顯示友好的錯(cuò)誤消息而不是異常跟蹤.請參閱 http://www.php.net/set-exception-handler 了解有關(guān)怎么做.
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.
這篇關(guān)于函數(shù)中的 PDO try-catch 用法的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!