封装分页类
结合之前的 BaseObject 封装一个分页类
<?php
namespace common\web;
use yii\base\BaseObject;
use yii\data\Pagination;
/**
* 分页类
*
* @author vogin
*
*/
class Paginator extends BaseObject
{
// 分页对象
private $_page;
// 分页数据
private $_list;
// 页数
private $_pageSize;
// 默认页数
private $_defaultPageSize = 10;
public function setPage ($page)
{
$this->_page = $page;
}
public function getPage ()
{
return $this->_page;
}
public function setList ($list)
{
$this->_list = $list;
}
public function getList ()
{
return $this->_list;
}
public function setPageSize ($pageSize)
{
$this->_pageSize = $pageSize;
}
public function getPageSize ()
{
return $this->_pageSize;
}
/**
* 实例
*/
public static function getInstance ()
{
return new Paginator();
}
/**
* 获取每页数量
*
* @return int
*/
private function pageSize ()
{
if(is_null($this->_pageSize))
{
return $this->_defaultPageSize;
}
return $this->_pageSize;
}
/**
* 分页
*/
public function pagination ($query)
{
// 总条数
$count = $query->count();
// 响应全部的datatable的参数内容
// 此内容由前端传递,为pageSize
$pageSize = Requestor::post('length', $this->pageSize());
// Yii自带分页类
$page = new Pagination([
'pageSize' => $pageSize,
'totalCount' => $count
]);
// offset, limit
// offset 起始内容从前端传递
$offset = Requestor::post('start', - 1);
if(- 1 == $offset)
{
$offset = $page->offset;
}
$limit = $page->limit;
// 数据列表
$list = $query->offset($offset)->limit($limit)->all();
// 设置
$this->_page = $page;
$this->_list = $list;
return $this;
}
}
逻辑方法
<?php
class Banner extends ActiveRecord {
public static function pager(){
// 查询数据
$query = new Query();
$query->from(Banner::tableName());
// 进行分页
$paginator = Paginator::getInstance();
$paginator->pagination($query);
return $paginator;
}
}
使用
<?php
class BannerController extends Controller {
public function actionList() {
$paginator = Banner::pager();
return Result::success([
"count" => $paginator->page->totalCount,
"data" => $paginator->list
]);
}
}