在ZendFramework2中,可以方便地使用\Zend\Paginator\Paginator类来实现分页功能。
\Zend\Paginator\Paginator类需要使用\zend\Paginator\Adapter\DbSelect对象从数据库获取数据(如果要从数组获取数据,就用\Zend\Paginator\Adapter\ArrayAdapter)。
use Zend\Db\Sql\Select;
use Zend\Paginator\Adapter\DbSelect;
use Zend\Paginator\Paginator;
//创建Zend\Paginator\Paginator对象
$select = new Select('user');//为user表创建查询对象
$resultSetPrototype = new ResultSet();//创建查询结果集原型对象
$resultSetPrototype->setArrayObjectPrototype(new User());
$paginatorAdapter = new DbSelect( //创建数据源对象
$select, //查询对象
$this->tableGateway->getAdapter(),//数据表适配器对象
$resultSetPrototype//查询结果集原型对象
);
$paginator = new Paginator($paginatorAdapter);//用数据源对象初始化创建分页器对象
\Zend\Paginator\Paginator每次从数据库获取数据的时候,不是一次获取所有行,而是只获取当前页的行。
假设配置的路由为/user/list/xxx,如下:
'routes' => array(
'user' => array(
'type' => 'segment',
'options' => array(
'route' => '/user[/][:action][/:id]',
'constraints' => array(
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
'id' => '[0-9]+',
),
'defaults' => array(
'controller' => 'User\Controller\User',
'action' => 'list',
),
),
),
),
那么控制器可以这样从url中获取当前页:
$pagenum = (int)$this->params()->fromRoute('id', 1);
然后,直接使用\Zend\Paginator\Paginator对象获取数据源交给View:
$paginator = $this->getUserTable()->getPaginator();
$paginator->setCurrentPageNumber($pagenum);//设置当前页
$paginator->setItemCountPerPage(15);//设置每页显示的页数
return new ViewModel(array(
'paginator' => $paginator
));
之后,在list.phtml中就可以直接显示当前页了:
<?php foreach ($this->paginator as $user) : ?>
<tr>
<td><?php echo $this->escapeHtml($user->name);?></td>
</tr>
<?php endforeach; ?>
可以通过\Zend\Paginator\Paginator对象的以下一些属性获取上一页、下一页、第一页、最后一页等等:
$this->first;//第一页页码
$this->previous;//前一页页码
$this->current;//当前页码
$this->next;//下一页页码
$this->last;//最后一页页码
$this->pageCount;//总页数
分页控制栏可以这样输出:
echo $this->paginationControl(
$this->paginator,
'sliding',//界面风格,有"All"、"Elastic"、"Jumping"、"Sliding"四种风格可选
array('user/partial/paginator.phtml', 'User'),//paginator.phtml是界面的html代码片段
array(
'route' => 'user'
);
在model/User/view目录下创建文件“paginator.phtml”,输入以下代码,即可创建一个Slider风格的分页控制栏:
<?php if ($this->pageCount): ?>
<div>
<ul class="pagination">
<!-- Previous page link -->
<?php if (isset($this->previous)): ?>
<li>
<a href="<?php echo $this->url($this->route, array('action' => 'list', 'id' => $this->previous)); ?>">
<<
</a>
</li>
<?php else: ?>
<li class="disabled">
<a href="#">
<<
</a>
</li>
<?php endif; ?>
<!-- Numbered page links -->
<?php foreach ($this->pagesInRange as $page): ?>
<?php if ($page != $this->current): ?>
<li>
<a href="<?php echo $this->url($this->route, array('action' => 'list', 'id' => $page));?>">
<?php echo $page; ?>
</a>
</li>
<?php else: ?>
<li class="active">
<a href="#"><?php echo $page; ?></a>
</li>
<?php endif; ?>
<?php endforeach; ?>
<!-- Next page link -->
<?php if (isset($this->next)): ?>
<li>
<a href="<?php echo $this->url($this->route, array('action' => 'list', 'id' => $this->next)); ?>">
>>
</a>
</li>
<?php else: ?>
<li class="disabled">
<a href="#">
>>
</a>
</li>
<?php endif; ?>
</ul>
</div>
<?php endif; ?>