“让两个数据库类并排运行是一种好习惯吗?” 不,这没有意义……?
我将使用可以轻松转移到另一个站点的特定 DB 类。我会使用 PDO 对象来实现这一点。settings.ini 应该存储在 webroot 之外,因为登录凭据等存储在那里。
<?php
class DB_Instance
{
private static $db;
public static function getDBO()
{
global $dbSettings;
global $dsn;
global $user;
global $password;
if (!self::$db)
//Get connection parameters from ini-file
$dbSettings = parse_ini_file('settings.ini', true);
$dsn = 'mysql:dbname=' . $dbSettings['database']['name'] . ';host=' . $dbSettings['database']['host'];
$user = $dbSettings['database']['user'];
$password = $dbSettings['database']['password'];
try {
$dbh = new PDO($dsn, $user, $password, array(PDO::ATTR_PERSISTENT => TRUE));
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->exec("set names utf8");
self::$db = $dbh;
return self::$db;
}
}
?>
然后由这样的类访问:
<?php
class Language {
private $languageId; //Language identifier
private $language; //Which language
private $dbInstance; //DBInstance
public function __construct($languageId = null) {
$this->dbInstance = DB_Instance::getDBO();
....
然后执行如下函数:
$statement = $dbInstance->{PDO function}
有关 PDO 类的更多信息,请查看:http ://www.php.net/manual/en/class.pdo.php