3

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!

Nicky Hajal
  • 1,584
  • 1
  • 15
  • 23

4 Answers4

4

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
  • 1,584
  • 1
  • 15
  • 23
3

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
  • 316
  • 1
  • 3
  • 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 May 07 '09 at 03:23
  • Haha, yeah I tend to defer to the API before reading through the docs. Thanks for pointing that out :) – stephenminded May 07 '09 at 03:32
  • 1
    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 May 07 '09 at 19:45
1

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');
}
bensiu
  • 24,660
  • 56
  • 77
  • 117
1

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
  • 17,549
  • 10
  • 60
  • 91