How use different database using zend in a single project

Now, it becomes more difficult if you have a different in how mysql connects to the two schemas. For example different users that each have access on one schema or two different servers.

So let’s start by setting up our test system.

In application.ini we remove the settings we used before and we replace it by the following:

resources.multidb.default.adapter = PDO_MYSQL = localhost
resources.multidb.default.username = root
resources.multidb.default.password = ****
resources.multidb.default.dbname = testdb1
resources.multidb.default.default = true

resources.multidb.another.adapter = PDO_MYSQL = localhost
resources.multidb.another.username = root
resources.multidb.another.password = ****
resources.multidb.another.dbname = testdb2
resources.multidb.another.default = false

In the bootstrap you add the _initDbRegistry block like below, this will add the different databases to the registry:

* Add databases to the registry
* @return void
public function _initDbRegistry()
$multidb = $this->getPluginResource('multidb');
Zend_Registry::set('db_default', $multidb->getDb('default'));
Zend_Registry::set('db_another', $multidb->getDb('another'));
return $multidb->getDb();

Seperated DB Calls

Let’s first see how we set everything up so we can access each database trough Zend_Db_Table.
Create two model class one is Exampledefault.php and Exampleanother.php. Two table are in different database.

class Exampledefault extends Zend_Db_Table_Abstract
protected $_name = 'exampledefault';
protected $_adapter = 'db_default';


class Exampleanother extends Zend_Db_Table_Abstract
protected $_name = 'exampleanother';
protected $_adapter = 'db_another';


How you can access from controller

Let’s create a helloworld controller.

* Initialize the Controller class
* @param void
* @return void
function init()
$this->table1 = new Exampledefault();
$this->table2 = new Exampleanother(Zend_Registry::get('db_another'));


Now you can access two different database in a single project.

Have a nice day!!!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s