設定預設連線服務
Phalcon 預設使用 db
服務來獲取與資料庫的連線。
假設你有一個設定了 database
欄位的配置檔案,你可以包含或自動載入以下程式碼以獲取與專案資料庫的連線:
$di->set('db', function () use ($config) {
$dbconf = $config->database;
switch(strtolower($dbconf->adapter)) {
case 'mysql':
return new \Phalcon\Db\Adapter\Pdo\Mysql(array(
'host' => $dbconf->host,
'username' => $dbconf->username,
'password' => $dbconf->password,
// default database to work with
'dbname' => $dbconf->dbname,
// default character set
'charset' => $dbconf->charset,
// connection warm-up commands for PDO
'options' => array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES "' . $dbconf->charset . '"',
PDO::ATTR_CASE => PDO::CASE_LOWER
)
));
case 'postgresql':
return new \Phalcon\Db\Adapter\Pdo\Postgresql(array(
'host' => $dbconf->host,
'username' => $dbconf->username,
'password' => $dbconf->password,
'dbname' => $dbconf->dbname,
'options' => array(
)
));
default:
throw new \Exception('Unimplemented database::adapter in config.ini');
}
});