We can use Zend multiDb resource to connect to multiple databases.
We'll need 1 default database adapter or it will fail. Also I like having the profiler with the FireBug console during testing, so you can set it to true if you want.
;application.ini
; Resources (DB)
resources.multidb.default.adapter = "pdo_mysql"
resources.multidb.default.host = "your_db_host"
resources.multidb.default.username = "your_db_user"
resources.multidb.default.password = "your_db_password"
resources.multidb.default.dbname = "your_db_name"
resources.multidb.default.charset = "utf8"
resources.multidb.default.profiler.enabled = false
resources.multidb.default.profiler.class = "Zend_Db_Profiler_Firebug"
resources.multidb.default.default = trueresources.multidb.another.adapter = "pdo_mysql"
resources.multidb.another.host = "another_db_host"
resources.multidb.another.username = "another_db_user"
resources.multidb.another.password = "another_db_password"
resources.multidb.another.dbname = "another_db_name"
resources.multidb.another.default = false
resources.multidb.another.charset = "utf8"
The first multidb (default) is set to default = true and the second multidb (another) has default set to false.
You can have as many multidb as you want.
In our Application/Bootstrap.php we'll have to register these Adapters, so we can call them in our code.
protected function _initDb()
{
$resource = $this->getPluginResource('multidb');
$resource->init();
$profiler = $resource->getDb()->getProfiler();
$profiler->setFilterQueryType(Zend_Db_Profiler::SELECT | Zend_Db_Profiler::INSERT | Zend_Db_Profiler::UPDATE);
Zend_Registry::set('default_db', $resource->getDb());
Zend_Registry::set('another_db', $resource->getDb('another'));
return $resource->getDb();
}
We call the multidb resource plugin and assign it to the Zend_Registry. You can skip the profiler if you don't want to use profiling.
Now for the fun part. If you have created a DbTable, let's say Default_Model_DbTable_Articles. And you want to use the adapter from multidb another. You can pass it to the constructor like this.
$table = new Default_Model_DbTable_Articles($adapter = Zend_Registry::get('another_db'));
That's all.
Pretty neat huh?
Add new comment