我正考虑在未来的所有webapp中使用PDO.目前(使用我迄今为止从SO中学到的东西),我在我的网站中处理数据库连接的是一个Singleton类,如下所示:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
和另一个具有内容特定功能的文件(functions.php)看起来完全像这样:
function get_recent_activities ()
{
try
{
$db = DB::getInstance();
// --prepare and execute query here, fetch the result--
return $my_list_of_recent_activities;
}
catch (PDOException …Run Code Online (Sandbox Code Playgroud)