3
votes

I mostly use zend_db_table with a paginator, the problem is that it will return zend_db_rows instead the domain objects from my datamapper.

Let's say :

class Content_Model_ArticleMapper {
/*
 * @param Zend_Db_Select $select
 * @return Zend_Paginator
 */
    public function getPaginator($select = null){}
}

I can hack it by overriding _loadAndReturnRow method in a custom rowset However this is pretty ugly as I don't have a Zend_Db_Row anymore when I query the table. And loose the methods too like save which I don't want to replicate on the domain object. :

class Content_Model_DbTable_Rowset_Articles extends Zend_Db_Table_Rowset {
        protected function _loadAndReturnRow($position)
    {
    if (!isset($this->_data[$position])) {
        require_once 'Zend/Db/Table/Rowset/Exception.php';
        throw new Zend_Db_Table_Rowset_Exception("Data for provided position does not exist");
    }

    // do we already have a row object for this position?
    if (empty($this->_rows[$position])) {

        $this->_rows[$position] = new Content_Model_Article($this->_data[$position]);
    }

    // return the row object
    return $this->_rows[$position];
    }
}

So my question how do you do this nicely ? :) Do you write custom Paginator adapters?

1
"Do you write custom Paginator adapters?", yes, I believe this is the only best practice. - Martijn

1 Answers

1
votes

You can set a rowClass in your DbTable like

DbTable

class Content_Model_DbTable_Article extends Zend_Db_Table_Abstract {

    protected $_name = 'article';

    public function init() {
        $this->setRowClass('Content_Model_Article');
    }

}

Domain Model

class Content_Model_Article extends Zend_Db_Table_Row {

    //for example
    public function getAuthorFullName() {
        return $this->author_firstname . ' ' . $this->author_lastname;
    }

}

Now rows in your rowset are instances of Content_Model_Article and you can use the Zend_Paginator_Adapter_Iterator.

Using Paginator

$articleTable = new Content_Model_DbTable_Article();
$articleRowset = $articleTable->fetchAll();
$paginator = new Zend_Paginator(Zend_Paginator_Adapter_Iterator($articleRowset));
//now you can loop through the paginator
foreach($paginator as $article) {
    echo $article->getAuthorFullName();
}