Multiple database in zend framework



Zend framework has two levels of abstraction databases and tables. The database abstraction keeps your PHP code independent from database server you use. It means that it is easier for an application to support multiple database
servers. To use multiple database in zend framework we need to zend resource plugin ‘multidb’.

You can use it in application.ini file as follows:

resources.multidb.db1.adapter = "pdo_mysql"
resources.multidb.db1.host    = "localhost"
resources.multidb.db1.username  = "root"
resources.multidb.db1.password  = ""
resources.multidb.db1.dbname   = "db1"
resources.multidb.db1.charset = "utf8"
resources.multidb.db1.driver_options.1002 = "SET NAMES utf8"
resources.multidb.db1.default = true

resources.multidb.db2.adapter = "pdo_mysql"
resources.multidb.db2.host = "localhost"
resources.multidb.db2.username = "root"
resources.multidb.db2.password = ""
resources.multidb.db2.dbname   = "db2"
resources.multidb.db2.charset = "utf8"
resources.multidb.db2.driver_options.1002 = "SET NAMES utf8"
resources.multidb.db2.default  = false

Now in bootstrap file you need to add database adapters to the registry by adding following code:

protected function _initDbAdaptersToRegistry()
{
	$this->bootstrap('multidb');
	$resource = $this->getPluginResource('multidb');
				
	$Adapter1 = $resource->getDb('db1');
	$Adapter2 = $resource->getDb('db2');		
	Zend_Registry::set('db1', $Adapter1);
	Zend_Registry::set('db2',$Adapter2);
}

Now both database adapters has been added to the zend registry. Database db1 will be our default database, As we have set db1 as default database in application.ini by adding this line

resources.multidb.db1.default = true

Now If you need to use db2 database just create use Zend_Registry::get(‘db2’) registry.

Hope this will help you!