在上一篇《在Laravel外使用Eloquent(一)》 中我们演示了如何引入Eloquent以及基本使用,但是如果细心的朋友肯定会发现,当你在使用paginate(15)来分页的时候是会报错的。因为我们没有依赖laravel的pagination模块。但是引入那个模块同时它内部依赖了symfony的http-foundation模块,意味着为了一个分页功能我们要装好多东西。于是我就实现了一个比较简单的分页类:
代码见:https://github.com/overtrue/rester
php
<?php namespace Rester; /** * Paginator.php * * (c) 2014 overtrue <anzhengchao@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * @author overtrue <anzhengchao@gmail.com> * @github https://github.com/overtrue * @url http://overtrue.me * @date 2014-10-23T20:05:33 */ use Closure; use Countable; use ArrayAccess; use Serializable; use ArrayIterator; use JsonSerializable; use IteratorAggregate; class Paginator implements ArrayAccess, Countable, IteratorAggregate, Serializable, JsonSerializable { protected $pager; protected $pageSize; protected $total; protected $items; /** * Constructor * * @param \Slim\Http\Request $request * @param string $pager */ public function __construct($pager = 'page') { $this->pager = $pager; } /** * Make a pagination * * @param array $items * @param integer $total * @param integer $pageSize * * @return array */ public function make($items, $total, $pageSize = 10) { $this->total = abs($total); $this->pageSize = $pageSize; $this->items = $items; return $this; } /** * Return current page * * @return integer */ public function getCurrentPage($total = null) { $page = a