设置默认连接服务

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');
    }
});