views:

196

answers:

4

I have 2 databases that my site uses including a central user database that relates to other site-specific databases.

Sometimes it is adequate to call new User(array('db'=>'adapter1')); (but never convenient); other times, though, such as when declaring relationships between tables on different databases, there is no way to do this.

Does anyone know a way to specify which database adapter to use from within the Zend_Db_Table_Abstract class?

Thanks!

A: 

You could set the class variable $_db to the correct adapter in the constructor.

global $adapter1; //There are better ways than using a global variable

$this->_db = $adapter1;

Assuming the adapter object can be referenced in the constructor. That doesn't seem to portable, but I believe it would work.

Tim Lytle
True - but use Zend_Registry instead of globals!
David Caunt
Yes, of course, that's why I put a comment in the code; however, it seemed the most clear and simple way to illustrate the method.
Tim Lytle
+2  A: 

Zend_Db_Table_Abstract provides a static method to set the default database adapter. Do this as follows:

Zend_Db_Table_Abstract::setDefaultAdapter($adapter);

Now, all your Table objects will use your adapter by default.

Note: the online docs sometimes don't make this obvious, so your second best place to check is in the API here: http://framework.zend.com/apidoc/core/

stephenminded
While the docs are sometimes a little vague and confusing, this one happens to be mentioned right out in the blue! http://framework.zend.com/manual/en/zend.db.table.html
blockhead
Haha, yeah I tend to defer to the API before reading through the docs. Thanks for pointing that out :)
stephenminded
I believe he wanted to set different table classes to different adapters (he uses two adapters). My understanding is that setting a default adapter will make all the tables use a single adapter.
Tim Lytle
A: 

Getting back to this pretty late, but none of the answers here quite did it for me. A select few of my database models needed to use 'tdb' and the following code was added to each of those classes to have that happen automatically:

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

I thank you all for your suggestions along the way!

Nicky Hajal
A: 

The init function can be used, it is not used in Zend_Db_Adapter_Abstract, can be used in your class to setup whatever needs to be done. _setAdapter accepts a string naming a Registry Key.

public function init()
{
    $this->_setAdapter('tdb');
}
Andrew de Thame