uniqueHxC uniqueHxC - 1 month ago 8
PHP Question

Zend Framework - Db Adapter in constructor is null

ZF Version: 1.11.2

I want to create an abstract class, which holds my db adapter. Simplified it looks like this:

<?php
class Application_Model_DbTable_Abstract extends Zend_Db_Table_Abstract
{
protected $_dbAdapter = null;

/**
* @return null
*/
public function getDbAdapter()
{
return $this->_dbAdapter;
}

/**
* @param null $dbAdapter
*/
public function setDbAdapter($dbAdapter)
{
$this->_dbAdapter = $dbAdapter;
}

public function __construct()
{
\Zend_Debug::dump($this->getAdapter(), 'Datei: ' . __FILE__ . '<br/>Zeile: ' . __LINE__, true); die;
}
}


But my dump returns null. In a basic model class (which extends from Zend_D b_Table_Abstract) the same dump returns an Zend_Db_Adapter_Pdo_Mysql object. Why?

Answer

I had a little look at the Zend DB source code just to refresh my memory. If you change your constructor to this:

public function __construct($config = array())
{
    parent::__construct($config);

    \Zend_Debug::dump($this->getAdapter(), 'Datei: ' . __FILE__ . '<br/>Zeile: ' . __LINE__, true); die;
}

It should work more like you're expecting.

Answering the question from your comment: the getAdapter() method of Zend_Db_Table_Abstract simply returns whatever's in the DB adapter variable. It doesn't do anything with the default. Also, since your class overrides that method, your version will be used instead.

The constructor in the Zend_Db_Table_Abstract class will set a default if one wasn't provided, so calling the parent constructor as in my example should ensure a default adapter is set.

Also, ZF1 is past end of life. You shouldn't use it for new applications, and should be planning migration for current ones.

Comments