在Laravel外使用Eloquent(二)- 分页问题

本文介绍了在不依赖Laravel完整框架的情况下,如何解决Eloquent ORM分页问题。作者提到在使用`paginate(15)`时会遇到错误,因为缺少laravel的pagination模块。为避免引入大量依赖,作者提供了一个简单的分页类实现,并在GitHub上分享了代码(https://github.com/overtrue/rester)。通过这个解决方案,读者可以在自己的项目中无缝使用Eloquent进行分页操作。
摘要由CSDN通过智能技术生成

在上一篇《在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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值