封装分页类

结合之前的 BaseObject 封装一个分页类

  1. <?php
  2. namespace common\web;
  3. use yii\base\BaseObject;
  4. use yii\data\Pagination;
  5. /**
  6. * 分页类
  7. *
  8. * @author vogin
  9. *
  10. */
  11. class Paginator extends BaseObject
  12. {
  13. // 分页对象
  14. private $_page;
  15. // 分页数据
  16. private $_list;
  17. // 页数
  18. private $_pageSize;
  19. // 默认页数
  20. private $_defaultPageSize = 10;
  21. public function setPage ($page)
  22. {
  23. $this->_page = $page;
  24. }
  25. public function getPage ()
  26. {
  27. return $this->_page;
  28. }
  29. public function setList ($list)
  30. {
  31. $this->_list = $list;
  32. }
  33. public function getList ()
  34. {
  35. return $this->_list;
  36. }
  37. public function setPageSize ($pageSize)
  38. {
  39. $this->_pageSize = $pageSize;
  40. }
  41. public function getPageSize ()
  42. {
  43. return $this->_pageSize;
  44. }
  45. /**
  46. * 实例
  47. */
  48. public static function getInstance ()
  49. {
  50. return new Paginator();
  51. }
  52. /**
  53. * 获取每页数量
  54. *
  55. * @return int
  56. */
  57. private function pageSize ()
  58. {
  59. if(is_null($this->_pageSize))
  60. {
  61. return $this->_defaultPageSize;
  62. }
  63. return $this->_pageSize;
  64. }
  65. /**
  66. * 分页
  67. */
  68. public function pagination ($query)
  69. {
  70. // 总条数
  71. $count = $query->count();
  72. // 响应全部的datatable的参数内容
  73. // 此内容由前端传递,为pageSize
  74. $pageSize = Requestor::post('length', $this->pageSize());
  75. // Yii自带分页类
  76. $page = new Pagination([
  77. 'pageSize' => $pageSize,
  78. 'totalCount' => $count
  79. ]);
  80. // offset, limit
  81. // offset 起始内容从前端传递
  82. $offset = Requestor::post('start', - 1);
  83. if(- 1 == $offset)
  84. {
  85. $offset = $page->offset;
  86. }
  87. $limit = $page->limit;
  88. // 数据列表
  89. $list = $query->offset($offset)->limit($limit)->all();
  90. // 设置
  91. $this->_page = $page;
  92. $this->_list = $list;
  93. return $this;
  94. }
  95. }

逻辑方法

  1. <?php
  2. class Banner extends ActiveRecord {
  3. public static function pager(){
  4. // 查询数据
  5. $query = new Query();
  6. $query->from(Banner::tableName());
  7. // 进行分页
  8. $paginator = Paginator::getInstance();
  9. $paginator->pagination($query);
  10. return $paginator;
  11. }
  12. }

使用

  1. <?php
  2. class BannerController extends Controller {
  3. public function actionList() {
  4. $paginator = Banner::pager();
  5. return Result::success([
  6. "count" => $paginator->page->totalCount,
  7. "data" => $paginator->list
  8. ]);
  9. }
  10. }