Search code examples
zend-frameworkzend-dbzend-db-table

Zend MultiDB adapters are not getting switched


i am having some problem with zend multidb. My adapters are not getting switched and which ever i sets as default is getting used every time. And also its not giving me any error as well. Following is the code i am using for zend multidb feature.

Bootstrap.php

public function _initDB()
{
    Zend_Registry::getInstance();       
    $this->bootstrap('multidb');
    $multidb = $this->getPluginResource('multidb');
    Zend_Registry::set('dbR', $multidb->getDb('dbR'));
    Zend_Registry::set('dbW', $multidb->getDb('dbW'));


}

Application.ini

resources.multidb.dbR.adapter = "mysqli"
resources.multidb.dbR.host = "xxx.xxx.x.xx"
resources.multidb.dbR.username = "root"
resources.multidb.dbR.password = "admin"
resources.multidb.dbR.dbname = "test_app1"
resources.multidb.dbR.profiler = "false"
resources.multidb.dbR.isDefaultTableAdapter = "true"

resources.multidb.dbW.adapter = "mysqli"
resources.multidb.dbW.host = "xxx.xxx.x.xx"
resources.multidb.dbW.username = "root"
resources.multidb.dbW.password = "admin"
resources.multidb.dbW.dbname = "test_app2"

Now in my model class i use following line of code where i wants to perform any write operation

class Abc_Model_ModelName extends Zend_Db_Table_Abstract
{
    protected $_dbR;
    protected $_dbW;
    protected $_name = 'table_name';


    public function init(){
        $this->_dbR = Zend_Registry::get("dbR");
        $this->_dbW = Zend_Registry::get("dbW");
    }

    public function addedit($data = array())
    {
         $this->setDefaultAdapter($this->_dbW);

    }
}

can anyone help me out with this?


Solution

  • I believe you need to call $this->_setAdapter($reader); instead of setDefaultAdapter() function.

    _setAdapter will set the new adapter to the existing db table, while setDefaultAdapter() will only set the default adapter that will be used from now on.

    Something like:

    /**
     * Returns an instance of a Zend_Db_Table_Select object.
     *
     * @param bool $withFromPart Whether or not to include the from part of the select based on the table
     * @return Zend_Db_Table_Select
     */
    public function slaveSelect($withFromPart = self::SELECT_WITHOUT_FROM_PART)
    {
        $reader = $this->_getMultiDb()->getRandomReadOnlyAdapter();
        $this->_setAdapter($reader);
        return parent::select($withFromPart);
    }