资讯专栏INFORMATION COLUMN

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

junfeng777 / 1554人阅读

摘要:在上一篇在外使用一中我们演示了如何引入以及基本使用,但是如果细心的朋友肯定会发现,当你在使用来分页的时候是会报错的。但是引入那个模块同时它内部依赖了的模块,意味着为了一个分页功能我们要装好多东西。

在上一篇《在Laravel外使用Eloquent(一)》 中我们演示了如何引入Eloquent以及基本使用,但是如果细心的朋友肯定会发现,当你在使用paginate(15)来分页的时候是会报错的。因为我们没有依赖laravel的pagination模块。但是引入那个模块同时它内部依赖了symfony的http-foundation模块,意味着为了一个分页功能我们要装好多东西。于是我就实现了一个比较简单的分页类:

代码见:https://github.com/overtrue/rester

php
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @author overtrue 
 * @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 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 = abs(app()->request->get("page", 1));

        if ($total) {
            $this->total = $total;
        }

        $page >= 1 || $page = 1;

        if ($this->items) {
            $totalPage = $this->getTotalPage();
            $page <= $totalPage || $page = $totalPage;
        }

        return $page;
    }

    /**
     * Return total pages
     *
     * @return integer
     */
    public function getTotalPage()
    {
        $this->pageSize > 0 || $this->pageSize = 10;

        $totalPage = ceil($this->total / $this->pageSize);

        $totalPage >= 1 || $totalPage = 1;

        return $totalPage;
    }

    public function links()
    {
        $html = "
    "; $totalPage = $this->getTotalPage(); $currentPage = $this->getCurrentPage(); if ($totalPage < 10) { for ($i = 1; $i <= $totalPage; $i++) { $active = $i == $currentPage ? "class="active"":""; $html .= "
  • $i
  • "; } } else { if ($currentPage > 3) { $html .= "
  • «
  • "; $start = $currentPage - 2; } else { $start = 1; } for ($i = $start; $i <= $currentPage; $i++) { $active = $i == $currentPage ? "class="active"":""; $html .= "
  • $i
  • "; } for ($i = $currentPage + 1; $i <= $currentPage + 3; $i++) { $active = $i == $currentPage ? "class="active"":""; $html .= "
  • $i
  • "; } if ($totalPage - $currentPage >= 5) { $html .= "
  • ...
  • "; $html .= "
  • $totalPage
  • "; } } return $html .= "
"; } /** * getLink * * @param integer $page * * @return string */ public function getLink($page) { static $query; if (is_null($query)) { $query = app()->request->get(); } $query["page"] = $page; return "?" . http_build_query($query); } /** {@inhertDoc} */ public function jsonSerialize() { return $this->items; } /** {@inhertDoc} */ public function serialize() { return serialize($this->items); } /** {@inhertDoc} */ public function unserialize($data) { return $this->items = unserialize($data); } /** {@inhertDoc} **/ public function getIterator() { return new ArrayIterator($this->items); } /** {@inhertDoc} */ public function count($mode = COUNT_NORMAL) { return count($this->items, $mode); } /** * Get a data by key * * @param string $key * * @return mixed */ public function __get($key) { return $this[$key]; } /** * Assigns a value to the specified data * * @param string $key * @param mixed $value * * @return void */ public function __set($key, $value) { $this->items[$key] = $value; } /** * Whether or not an data exists by key * * @param string $key * * @return bool */ public function __isset($key) { return isset($this->items[$key]); } /** * Unsets an data by key * * @param string $key */ public function __unset($key) { unset($this->items[$key]); } /** * Assigns a value to the specified offset * * @param string $offset * @param mixed $value * * @return void */ public function offsetSet($offset, $value) { $this->items[$offset] = $value; } /** * Whether or not an offset exists * * @param string $offset * * @access public * * @return bool */ public function offsetExists($offset) { return isset($this->items[$offset]); } /** * Unsets an offset * * @param string $offset * * @return array */ public function offsetUnset($offset) { if ($this->offsetExists($offset)) { unset($this->items[$offset]); } } /** * Returns the value at specified offset * * @param string $offset * * @return mixed */ public function offsetGet($offset) { return $this->offsetExists($offset) ? array_get($this->items, $offset) : null; } } ``` 然后在我们初始化eloquent的方装载这个分页类到eloquent中就好: ```php //... use ResterPaginator; // 注册分页类 Capsule::setPaginator(function() use ($app, $config) { return new Paginator($app->request, $config->get("pager", "page")); }); //... ``` 完整的eloquent初始化步骤请参考: https://github.com/overtrue/rester/blob/master/start/eloquent.php 然后我们就可以正常使用分页功能了: ```php $users = User::paginate(15); $users = User::where("status", 1)->paginate(15); ... ``` 因为上面的分页类实现了常用的[预定义接口](http://php.net/manual/zh/reserved.interfaces.php), 所以你可以很方便的使用分页结果: ```php // 遍历 foreach ($users as $user) { // do sth. } // json encode $json = json_encode($users); // count $count = count($users); //... ``` 另外还考虑到了大家不一定全用它写接口用,所以分页类同样实现了Laravel里的生成分页链接的方法:`$users->links()`, 它会生成bootstrap格式的分页列表: ```html ``` demo: ```php
name; ?>
links(); ?>

OK,那么现在你就可以很方便的在你的项目里无忧的使用Eloquent啦。

  

原文: http://overtrue.me/2014/11/25/using-eloquent-outsite-laravel-2.html

  

上一篇:http://segmentfault.com/blog/overtrue/1190000002468218

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/31907.html

相关文章

  • laravel5.5手写教程4Eloquent ORM分页及软删除

    摘要:从而达到了软删除。不过,你可以通过在查询中调用方法来强制查询已被软删除的模型方法也可以被用在关联查询只取出软删除数据会只取出软删除数据恢复被软删除的模型有时候你可能希望取消删除一个已被软删除的模型。 Laravel 有三宝,路由、容器和 Eloquent ORM,Eloquent ORM。我个人一直比较推荐于在实际操作中学习,之前简单了解了路由和Eloquent ORM的基本用法,今天...

    mindwind 评论0 收藏0
  • 【整理】LaravelEloquent ORM 相关操作

    摘要:软删除当模型被软删除后,它们并没有真的从数据库删除,而是在模型上设置一个属性并插入数据库,如果模型有一个非空值,那么该模型已经被软删除了。 Laravel 中Eloquent ORM 相关操作 定义 操作 获取(查询) 获取集合,(查询列表) 返回值是 IlluminateDatabaseEloquentCollection 的一个实例 获取所有的数据 use AppUser; $us...

    dongfangyiyu 评论0 收藏0
  • Lumen 初体验(

    摘要:的现状目前是版本,是基于开发。入口文件启动文件和配置文件框架的入口文件是。在路由中指定控制器类必须写全命名空间,不然会提示找不到类。目前支持四种数据库系统以及。使用时发生错误,因为在文件中,的默认驱动是。 最近使用 Lumen 做了 2 个业余项目,特此记录和分享一下。 Lumen 的介绍 在使用一项新的技术时,了解其应用场景是首要的事情。 Lumen 的口号:为速度而生的 La...

    Cheriselalala 评论0 收藏0
  • laravel手动创建数组分页

    摘要:目前,无法高效执行使用语句的分页操作。如果你需要在分页结果集中使用,建议你查询数据库并手动创建分页器。手动创建分页如果你想手动创建分页实例并且最终得到一个数组类型的结果,可以根据需求来创建或者实例来实现。 showImg(https://segmentfault.com/img/bVbbGos?w=640&h=400); laravel分页功能: 有几种方法可以对数据进行分页。最简单的...

    acrazing 评论0 收藏0
  • Laravel 5.7 正式发布,同时启动中文翻译

    摘要:版本现在正式发布了,每个人都可以使用。该版本引入了一些新特性并修复了很多,改进超过了版本。我们正在翻译中文文档,这是个系统性学习的好机会,感兴趣的同学请前往 showImg(https://segmentfault.com/img/remote/1460000016281269); 「Laravel 5.7 」版本现在正式发布了,每个人都可以使用。该版本引入了一些新特性并修复了很多 b...

    Yujiaao 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<