Zend Multi Db

OK So i’ve been writing an app that make heavy use of Zend_Db, across multiple databases using the MultiDb plugin.
Here’s a rough guide of how to set it up.

Now 1st rule I have in any MVC project is to always extend Zend_Db_Table with some form of Abstract class which you then further extend. This gives you a space to provide common functionality across all of your models. So I’ve created 2 extra classes inside the library/App/Db folder and called them App_Db_AbstractTable and App_Db_AbstractRow respoectively. This way I can override any of the initiation logic from Zend for all model classes and provide common methods to all my models. Without these classes this code would need to be duplicated across all my models.

I created two separate connection strings in my config, which looks like this:

; database connection 1
resources.multidb.name1.adapter = PDO_MYSQL
resources.multidb.name1.dbname = 12312423_mydb
resources.multidb.name1.username = 12312423_user
resources.multidb.name1.password = "password"
resources.multidb.name1.host = "mysql50-xx.wc2.dfw1.stabletransit.com"
resources.multidb.name1.default = true

resources.multidb.name2.adapter = PDO_MYSQL
resources.multidb.name2.dbname = 444444_db2
resources.multidb.name2.username = 444444_dbuser2
resources.multidb.name2.password = "7213d8TShkd478"
resources.multidb.name2.host = "mysql50-xx.wc2.dfw1.stabletransit.com" - different cloud machine

In my bootstrap for the entire application I initialise the MultiDb plugin to store these adapters in the registry thus:

	protected function _initDbAdaptersToRegistry()
	{
		$this->bootstrap('multidb');
		$resource = $this->getPluginResource('multidb');
		$resource->init();
				
		$Adapter1 = $resource->getDb('name1');
		$Adapter2 = $resource->getDb('name2');		
		Zend_Registry::set('Adapter1RegKey', $Adapter1);
		Zend_Registry::set('Adapter2RegKey',$Adapter2);
		
	}

In that method you can also stuff in some profiller initialisation code too if you use it etc etc.

Then in the App_Db_Abstract I setup the database adapter.

class Model_User extends App_Db_AbstractTable
{
	protected $_rowClass = 'User';
	
	protected $_name = 'table_name';
	
	protected $_schema = '';
	
	protected $_adapter = 'Adapter1RegKey';

I override the _setupDatabaseAdapter() method in the App_Db_AbstractTable to set the adapter as an object direct from the registry.

	protected function _setupDatabaseAdapter() 
	{
		$this->_db = Zend_Registry::get($this->_adapter);
	}

There’s MultiDb set up and working. Hope that helps.

4 responses to “Zend Multi Db

  1. Pingback: 2010 in review | jameshd – web ramblings

  2. Hi, I get stuck on multidb planning and the idea I got most is the overrideof _setupDatabaseAdapter(), Its helpful.

    Thanks

  3. Very useful! Clean solution to multi db setup and Zend Application.

  4. Pingback: DB Adapter eines Models (Modules) ändern - Zend Framework Forum - ZF1 / ZF2

Leave a comment