我试图在我的bootstrap.php文件中注册我的默认数据库适配器,以便我可以在任何地方访问它。这是我到目前为止的代码:
//bootstrap.php
protected function _initDb()
{
$dbAdapter = Zend_Db::factory(Zend_Registry::get('configuration')
->resources->db->adapter,
Zend_Registry::get('configuration')
->resources->db->params->toArray());
Zend_Registry::set('dbAdapter', $dbAdapter);
Zend_Db_Table_Abstract::setDefaultAdapter($dbAdapter);
}
然后我试着在我的一个模型中调用它:
//exampleModel.php
$select = $this->_getDbAdapter()
->select()
->from(array('t' => $this->_getTable()->getName()),
array('name'))....
然而,我只是得到错误:
Call to undefined method Application_Model_Example::_getdbAdapter() in...
显然它在我当前的类中寻找它,但是找不到它。
你需要在你的Model_Example
public function _getSqlAdapter()
{
return Zend_Registry::get('dbAdapter');
}
或者直接调用Zend_Db_Table::getDefaultAdapter()
而不是$this->_getDbAdapter()
在提供的代码中,您似乎没有从注册表调用适配器。您需要使用Zend_Registry::get('dbAdapter');
Application_Model_Example扩展了什么类?
我有Zend_Db_Table::setDefaultAdapter($dbAdapter);
在我的引导(注意它的Zend_Db_Table
,而不是Zend_Db_Table_Abstract
)。
然后在我的模型中,我会使用
$select = $this->->select()
->from(array('t' => $this->_getTable()->getName()), array('name'))....
假设你的模型扩展了Zend_Db_Table
?