我真的需要一個解決方案中,我可以使用類的Zend_Db_Table方法,爲我的分頁程序適配器的資源,而不是一個數組或對象Zend_Db_Select對象。
這種高級建模與Zend_Paginator的標準適配器不兼容。我繼續爲所有渴望得到答案的人解決這個問題,就像我一樣。
<?php
/* /zend/Paginator/Adapter/DbTableMethod.php */
class Zend_Paginator_Adapter_DbTableMethod implements Zend_Paginator_Adapter_Interface {
protected $_class;
protected $_method;
protected $_parameters;
protected $_rowCount = null;
public function __construct($class, $method, array $parameters = array()){
$reflectionClass = new ReflectionClass($class);
$reflectionMethod = $reflectionClass->getMethod($method);
$reflectionParameters = $reflectionMethod->getParameters();
$_parameters = array();
foreach ($reflectionParameters as $reflectionParameter){
$_parameters[$reflectionParameter->name] = ($reflectionParameter->isDefaultValueAvailable()) ? $reflectionParameter->getDefaultValue() : null;
}
foreach ($parameters as $parameterName => $parameterValue){
if (array_key_exists($parameterName, $_parameters)) $_parameters[$parameterName] = $parameterValue;
}
$this->_class = $class;
$this->_method = $method;
$this->_parameters = $_parameters;
}
public function count(){
if (is_null($this->_rowCount)){
$parameters = $this->_parameters;
$parameters['count'] = true;
$this->_rowCount = call_user_func_array(array($this->_class, $this->_method), $parameters);
}
return $this->_rowCount;
}
public function getItems($offset, $itemCountPerPage){
$parameters = $this->_parameters;
$parameters['limit'] = $itemCountPerPage;
$parameters['offset'] = $offset;
$items = call_user_func_array(array($this->_class, $this->_method), $parameters);
return $items;
}
}
?>
這是它如何在您的控制器:
<?php
class StoreController extends Zend_Controller_Action {
public function storeCustomersAction(){
$model = new Default_Model_Store();
$method = 'getStoreCustomers';
$parameters = array('storeId' => 1);
$paginator = new Zend_Paginator(new Site_Paginator_Adapter_DbTableMethod($model, $method, $parameters));
$paginator->setCurrentPageNumber($this->_request->getParam('page', 1));
$paginator->setItemCountPerPage(20);
$this->view->paginator = $paginator;
}
}
?>
此適配器工作的唯一要求是,以任何順序列出你的模型方法的參數列表如下參數([適配器將檢測通過反射方法簽名):
$極限= 0,$偏移量= 0,$計數=假
paginator會用$ limit,$ offset和$ count參數的相應值調用你的方法。而已!
例子:
<?php
class Default_Model_Store extends Zend_Db_Table {
public function getStoreCustomers($storeId, $includeCustomerOrders = false, $limit = 0, $offset = 0, $count = false){
if ($count) /* return SELECT COUNT(*) ... */
/* ... run primary query, get result */
$select = $this->_db->select(...)->limit($limit, $offset);
$rows = $this->_db->fetchAll($select);
if ($includeCustomerOrders){
foreach ($rows as &$row){
$customerId = $row['id'];
$row['orders'] = $this->getCustomerOrders($customerId);
}
}
return $rows;
}
}
?>
但不這似乎浪費了?調用getAll() - 一個昂貴的調用,可能會返回數千或數百萬條記錄 - 然後忽略20個左右,但您可能需要一頁顯示的數據? – 2010-10-20 14:28:53