FuelPHPでは、DBへの接続定義を, fuel/app/config/$ENV/db.phpで管理されています。
インストール直後の開発環境では、以下のようになってます。
return array(
'default' => array(
'connection' => array(
'dsn' => 'mysql:host=localhost;dbname=fuel_dev',
'username' => 'root',
'password' => 'root',
),
),
);
これを、複数DBへの接続対応するために、例えば’default2’を定義したうえで…
return array(
'default' => array(
'connection' => array(
'dsn' => 'mysql:host=localhost;dbname=fuel_dev',
'username' => 'root',
'password' => 'root',
),
),
'default2' => array(
'connection' => array(
'dsn' => 'mysql:host=localhost;dbname=fuel_dev2',
'username' => 'root',
'password' => 'root',
),
),
);
以下の形でSQLを発行してもエラーになってしまいます。
$sql = 'select * from tbl_test';
\DB::query($sql)->execute('default2');
出力されるエラーは下記の通りです。
Fuel\Core\FuelException [ Error ]:
Database type not defined in "default2" configuration or
"default2" configuration does not exist
fuel/core/classes/database/connection.php @ line 72
上記のエラーが発生する理由は、default以外のdb定義をする場合にはtypeの設定が必要なためです。
以下のような感じで
'type' => 'pdo',
の指定を追加すれば、エラーが解消されました。return array(
'default' => array(
'connection' => array(
'dsn' => 'mysql:host=localhost;dbname=fuel_dev',
'username' => 'root',
'password' => 'root',
),
),
'default2' => array(
'type' => 'pdo',
'connection' => array(
'dsn' => 'mysql:host=localhost;dbname=fuel_dev2',
'username' => 'root',
'password' => 'root',
),
),
);
上記のエラーが出ていた、fuel/core/classes/database/connection.phpの72行目を見ると、確かにtypeの定義がない時にエラーになっています。
if ( ! isset($config['type']))
{
throw new \FuelException('Database type not defined in "'.$name.'" configuration or "'.$name.'" configuration does not exist');
}
それでは、defaultの時のtypeはどこで指定されているのでしょうか?
調べてみると、
fuel\core\config\db.php
で指定が行われているようでした。ここに、DB検索を実行時にデータソースを指定しなければ
default
の定義が有効になる事と、default定義のtypeはpdoであることが記載されています。return array(
/*
* If you don't specify a DB configuration name when you create a connection
* the configuration to be used will be determined by the 'active' value
*/
'active' => 'default',
/**
* Base PDO config
*/
'default' => array(
'type' => 'pdo',
'connection' => array(
'dsn' => '',
'hostname' => '',
'username' => null,
'password' => null,
'database' => '',
'persistent' => false,
'compress' => false,
),
'identifier' => '`',
'table_prefix' => '',
'charset' => 'utf8',
'collation' => false,
'enable_cache' => true,
'profiling' => false,
'readonly' => false,
),
...
関連記事
コメントを残す