Phalcon uses db
service by default to obtain connection to databases.
Assuming you have an conguration file with database
field set up, you can include or autoload following code to obtain connection with database for your project:
$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');
}
});