Connecting to mulitple databases with DMZ DataMapper
I'm using the DMZ DataMapper ORM for CodeIgnite开发者_StackOverflowr.
I'm sure it is possible to configure it to connect to multiple databases. I haven't found any documentation yet. Has anyone done this before?
It's easy to set db parameters dynamically. This is what I use:
class DatamapperExt extends Datamapper {
public function __construct($id, $db) {
if ($db != null) {
// use these params as default - they don't change much.
$this->db_params = array_merge(array(
'dbdriver' => 'mysql',
'pconnect' => true,
'db_debug' => true,
'cache_on' => false,
'char_set' => 'utf8',
'cachedir' => '',
'dbcollat' => 'utf8_general_ci',
), $db);
parent::__construct($id);
}
}
Usage:
class YourModel extends DatamapperExt {
}
$db = array(
'hostname' => 'database_host',
'username' => 'database_username',
'password' => 'database_password',
'database' => 'database_name',
'prefix' => 'CI table_prefix - if any',
);
$your_model_with_diff_db = new YourModel(NULL, $db);
$model_with_id_diff_db = new YourModel(12, $db);
That's how I do it... it seems you have to specify db_params in the construct to make it work dynamically, otherwise datamapper goes off trying to construct/resolve relationships, etc. based on existing db settings.
If your db is set, and you don't need to modify parameters at runtime, you can also create a new entry in config/database.php:
$db['other_database'] = array(
'hostname' => 'database_host',
'username' => 'database_username',
'password' => 'database_password',
'database' => 'database_name',
'prefix' => 'CI table_prefix - if any',
)
(Note that my coding style above is different from standard CI for dbs.)
Then use with:
class YourModel extends DatamapperExt {
var $db_params = 'other_database';
}
Thank you for your idea indi.
in application/config/database.php
$db['other_database'] = array(
'hostname' => 'your_host_name',
'username' => 'your_user_name',
'password' => 'your_paasword',
'database' => 'other_database_name',
'prefix' => '',
'dbdriver' => 'mysql',
'pconnect' => true,
'db_debug' => true,
'cache_on' => false,
'char_set' => 'utf8',
'cachedir' => '',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'autoinit' => FALSE,
'stricton' => FALSE,
);
class Your_new_class extends Datamapper {
public $db_params = 'other_database';
}
The solution is simple:
Create another database configuration in database.php and add
var $db_params = 'name_of_other_database';
to the model.
精彩评论