我真的需要一个解决方案,在其中我可以使用 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;
}
}
?>
这个适配器工作的唯一要求是在你的模型方法参数列表中列出以下参数(以任何顺序[适配器将通过反射检测方法签名):
$limit = 0, $offset = 0, $count = false
分页器将使用 $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;
}
}
?>