phalcon使用的分页器是Phalcon\Paginator。
首先先展示一个比较完整的使用例子:
控制器代码:
use Phalcon\Paginator\Adapter\Model as Paginator;
$curPage = 1; if($this->request->isPost()) { $curPage = $this->request->getPost('page','int'); } else if($this->request->isGet()) { $curPage = $this->request->getQuery('page',"int"); } $posts = Posts::find(); if(count($posts) == 0) { $this->flash->notice("目前尚无任何帖子"); } $paginator = new Paginator(array( "data" => $posts, "limit" => 5, "page" => $curPage )); $this->view->page = $paginator->getPaginate();
视图代码:
<ul class="pager"> <li class="previous"> </li> <li class="next"> <?= $this->tag->linkTo('posts/post','发表帖子') ?> </li> </ul> <table class="table table-bordered table-striped" align="center"> <thead> <tr> <td>标题</td> <td>发布者</td> <td>发布时间</td> <td>评论数量</td> </tr> </thead> <tbody> <?php foreach($page->items as $post) { ?> <tr> <td><?= $this->tag->linkTo('posts/detail?pid='.$post->id,$post->title) ?></td> <td><?= $post->users->username ?></td> <td><?= date('Y-m-d H:i:s',$post->post_time) ?></td> <td><?= $post->comment_num ?></td> </tr> <?php } ?> </tbody> <tbody> <tr> <td colspan="4" align="right"> <div class="btn-group"> <span class="help-inline">共<?= $page->total_items ?>个帖子</span> <?= $this->tag->linkTo(array('posts/index',"第一页",'class'=>'icon-fast-backward btn')) ?> <?= $this->tag->linkTo(array('posts/index?page='.$page->before,"上一页",'class'=>'icon-fast-backward btn')) ?> <?= $this->tag->linkTo(array('posts/index?page='.$page->next,"下一页",'class'=>'icon-fast-backward btn')) ?> <?= $this->tag->linkTo(array('posts/index?page='.$page->last,"最后一页",'class'=>'icon-fast-backward btn')) ?> <span class="help-inline">第<?= $page->current ?>/<?= $page->total_pages ?>页</span> </div> </td> </tr> </tbody> </table>
该组件使用了适配器封装不同来源的数据,即“data”参数可以是一个数组,一个模型查询结果集对象,也可以是一个查询生成器,还可以使用自定义适配器。
使用例子:
use Phalcon\Paginator\Adapter\Model as PaginatorModel;
use Phalcon\Paginator\Adapter\NativeArray as PaginatorArray;
use Phalcon\Paginator\Adapter\QueryBuilder as PaginatorQueryBuilder;
// Passing a resultset as data
$paginator = new PaginatorModel(
array(
"data" => Products::find(),
"limit" => 10,
"page" => $currentPage
)
);
// Passing an array as data
$paginator = new PaginatorArray(
array(
"data" => array(
array('id' => 1, 'name' => 'Artichoke'),
array('id' => 2, 'name' => 'Carrots'),
array('id' => 3, 'name' => 'Beet'),
array('id' => 4, 'name' => 'Lettuce'),
array('id' => 5, 'name' => '')
),
"limit" => 2,
"page" => $currentPage
)
);
// Passing a querybuilder as data
$builder = $this->modelsManager->createBuilder()
->columns('id, name')
->from('Robots')
->orderBy('name');
$paginator = new PaginatorQueryBuilder(
array(
"builder" => $builder,
"limit" => 20,
"page" => 1
)
);
页面属性:
items:当前页面的每一项,next:下一页,last:最后一页,current:当前页面,before:上一页,total_pages:总页数,total_items:总项数。