2011-07-14 24 views
3

我主要使用zend_db_table與分頁器,問題是它會返回zend_db_rows,而不是我的數據映射器中的域對象。Zend框架數據映射器+分頁器

比方說:

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

我可以在自定義的行集 覆蓋_loadAndReturnRow方法破解它。然而,這是非常醜陋的,因爲我沒有Zend_Db_Row了,當我查詢表。 並鬆散的方法也保存,我不想複製域對象。 :

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]; 
    } 
} 

所以我的問題,你如何做到這一點很好? :)你是否編寫自定義Paginator適配器?

+0

「你編寫自定義分頁程序適配器?」是的,我相信這是唯一的最佳實踐。 – Martijn

回答

1

您可以像

DBTABLE在DBTABLE設置rowClass

class Content_Model_DbTable_Article extends Zend_Db_Table_Abstract { 

    protected $_name = 'article'; 

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

} 

域模型

class Content_Model_Article extends Zend_Db_Table_Row { 

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

} 

現在,在你的行集行是Content_Model_Article的情況下,你可以使用Zend_Paginator_Adapter_Iterator。

使用分頁程序

$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(); 
}