使用Zend_Paginator進行分頁

之前都是使用自已編寫的分頁,後來知道在1.6版本中新增了分頁的功能,所以花時間試了一下,感覺不錯,但不知道效率怎樣。現在先記一下,待日後再測試效率。

1.直接在controller中建立Zend_Paginator,並設定相關資料。

public function testAction()
{
 $db=Zend_Registry::get('db');
 $sql=$db->select()->from('news');
 $paginator=Zend_Paginator::factory($sql);
 $paginator->setCurrentPageNumber($this->_request->getParam('page'));
 $paginator->setItemCountPerPage(2);
 $this->view->paginator = $paginator;
 if(count($paginator))
 {
  $list='';
  foreach($paginator as $items)
  {
   $list.=$items['topic'];
  }
  $this->view->list=$list;
 }else{
  $this->view->list='no data';
 }
}

2.然後在test.phtml中輸出資料,並加入paginationControl這個view helper來輸出轉頁選單。

<html>
<body>
 <?=$this->list?>
 <?echo $this->paginationControl($this->paginator,'Sliding','page.phtml'); ?>
</body>
</html>

3.最後就是設定page.phtml,這個檔案將會輸出轉頁選單。

<?php if ($this->pageCount): ?>
<div class="paginationControl">
<!-- Previous page link -->
<?php if (isset($this->previous)): ?>
<a href="<?= $this->url(array('page' => $this->previous)); ?>">
< Previous
</a> |
<?php else: ?>
<span class="disabled">< Previous</span> |
<?php endif; ?>

<!-- Numbered page links -->
<?php foreach ($this->pagesInRange as $page): ?>
<?php if ($page != $this->current): ?>
<a href="<?= $this->url(array('page' => $page)); ?>">
<?= $page; ?>
</a> |
<?php else: ?>
<?= $page; ?> |
<?php endif; ?>
<?php endforeach; ?>

<!-- Next page link -->
<?php if (isset($this->next)): ?>
<a href="<?= $this->url(array('page' => $this->next)); ?>">
Next >
</a>
<?php else: ?>
<span class="disabled">Next ></span>
<?php endif; ?>
</div>
<?php endif; ?>

沒有留言: