Laravel5.1+ 分頁Pagination解析以及擴展

本文最先發表於本人博客: Laravel5.1+ 分頁Pagination解析以及擴展php

Laravel 的分頁很方便,其實擴展起來也挺容易的,下面就來作個示例,擴展一下paginate() simplePaginate()方法,來實現咱們自定義分頁樣式,好比顯示"上一頁""下一頁",而不是"《""》",固然擴展的方法掌握了你就能夠肆無忌憚的擴展一個你想要的分頁了,好比跳轉到某一頁,分頁顯示一共多少記錄,當前顯示的記錄範圍等等巴拉巴拉的。。。html

5.1和5.2應該是一樣的方法,我這裏用的是5.2的版本。文檔告訴咱們Paginator 對應於查詢語句構造器和 Eloquent 的 simplePaginate 方法,而 LengthAwarePaginator則等同於 paginate 方法。那咱們仍是來看下源碼,具體這個 paginate 是如何實現render()的,laravel

  • Illuminate/Pagination/LengthAwarePaginator.php
<?php

namespace Illuminate\Pagination;

......

class LengthAwarePaginator extends AbstractPaginator implements Arrayable, ArrayAccess, Countable, IteratorAggregate, JsonSerializable, Jsonable, LengthAwarePaginatorContract
{
......
    public function render(Presenter $presenter = null)
    {
        if (is_null($presenter) && static::$presenterResolver) {
            $presenter = call_user_func(static::$presenterResolver, $this);
        }

        $presenter = $presenter ?: new BootstrapThreePresenter($this);

        return $presenter->render();
    }
......
}

render()中傳入的是一個Presenter的實例,並調用這個實例化的render方法來實現分頁的顯示的。若是沒有則調用BootstrapThreePresenterrender()的,來看看BootstrapThreePresenter是幹嗎的web

  • Illuminate/Pagination/BootstrapThreePresenter.php
<?php

namespace Illuminate\Pagination;

use Illuminate\Support\HtmlString;
use Illuminate\Contracts\Pagination\Paginator as PaginatorContract;
use Illuminate\Contracts\Pagination\Presenter as PresenterContract;

class BootstrapThreePresenter implements PresenterContract
{
    use BootstrapThreeNextPreviousButtonRendererTrait, UrlWindowPresenterTrait;

    /**
     * The paginator implementation.
     *
     * @var \Illuminate\Contracts\Pagination\Paginator
     */
    protected $paginator;

    /**
     * The URL window data structure.
     *
     * @var array
     */
    protected $window;

    /**
     * Create a new Bootstrap presenter instance.
     *
     * @param  \Illuminate\Contracts\Pagination\Paginator  $paginator
     * @param  \Illuminate\Pagination\UrlWindow|null  $window
     * @return void
     */
    public function __construct(PaginatorContract $paginator, UrlWindow $window = null)
    {
        $this->paginator = $paginator;
        $this->window = is_null($window) ? UrlWindow::make($paginator) : $window->get();
    }

    /**
     * Determine if the underlying paginator being presented has pages to show.
     *
     * @return bool
     */
    public function hasPages()
    {
        return $this->paginator->hasPages();
    }

    /**
     * Convert the URL window into Bootstrap HTML.
     *
     * @return \Illuminate\Support\HtmlString
     */
    public function render()
    {
        if ($this->hasPages()) {
            return new HtmlString(sprintf(
                '<ul class="pagination">%s %s %s</ul>',
                $this->getPreviousButton(),
                $this->getLinks(),
                $this->getNextButton()
            ));
        }

        return '';
    }
......
}

這裏能夠看到BootstrapThreePresenter實現了PresenterContract 的接口,render() 纔是分頁顯示的真正實現,構造方法中的第一個參數PaginatorContract 其實就是一個Paginator咱們繼續看下PresenterContract也就是Presenter接口中定義了什麼方法須要實現app

  • illuminate/contracts/Pagination/Presenter.php
<?php

namespace Illuminate\Contracts\Pagination;

interface Presenter
{
    /**
     * Render the given paginator.
     *
     * @return \Illuminate\Contracts\Support\Htmlable|string
     */
    public function render();

    /**
     * Determine if the underlying paginator being presented has pages to show.
     *
     * @return bool
     */
    public function hasPages();
}

其中定義了renderhasPages方法須要實現ide

好了,那咱們如今已經很清晰了,咱們要自定義分頁的顯示,那麼就要寫一個咱們本身的Presenter來實現接口中的render()hasPages()就能夠了。this

首先就來簡單的實現一個paginate(),顯示出來"上一頁"和"下一頁",中間是分頁數字的例子。url

新建文件以下(我的習慣)app/Foundations/Pagination/CustomerPresenter.phpspa

<?php
namespace App\Foundations\Pagination;

use Illuminate\Contracts\Pagination\Presenter as PresenterContract;
use Illuminate\Contracts\Pagination\LengthAwarePaginator as PaginatorContract;
use Illuminate\Pagination\UrlWindow;
use Illuminate\Support\HtmlString;
use Illuminate\Pagination\BootstrapThreeNextPreviousButtonRendererTrait;
use Illuminate\Pagination\UrlWindowPresenterTrait;

class CustomerPresenter implements PresenterContract
{
    use BootstrapThreeNextPreviousButtonRendererTrait, UrlWindowPresenterTrait;

    protected $paginator;

    protected $window;

    /**
     * Create a new Bootstrap presenter instance.
     *
     * @param  \Illuminate\Contracts\Pagination\Paginator $paginator
     * @param  \Illuminate\Pagination\UrlWindow|null $window
     * @return void
     */
    public function __construct(PaginatorContract $paginator, UrlWindow $window = null)
    {
        $this->paginator = $paginator;
        $this->window = is_null($window) ? UrlWindow::make($paginator) : $window->get();
    }

    /**
     * Determine if the underlying paginator being presented has pages to show.
     *
     * @return bool
     */
    public function hasPages()
    {
        return $this->paginator->hasPages();
    }

    /**
     * Convert the URL window into Bootstrap HTML.
     *
     * @return \Illuminate\Support\HtmlString
     */
    public function render()
    {
        if ($this->hasPages()) {
            return new HtmlString(sprintf(
                '<ul class="pagination">%s %s %s</ul>',
                $this->getPreviousButton('上一頁'),//具體實現能夠查看該方法
                $this->getLinks(),
                $this->getNextButton('下一頁')//具體實現能夠查看該方法
            ));
        }

        return '';
    }

    /**
     * Get HTML wrapper for an available page link.
     *
     * @param  string $url
     * @param  int $page
     * @param  string|null $rel
     * @return string
     */
    protected function getAvailablePageWrapper($url, $page, $rel = null)
    {
        $rel = is_null($rel) ? '' : ' rel="' . $rel . '"';

        return '<li><a href="' . htmlentities($url) . '"' . $rel . '>' . $page . '</a></li>';
    }

    /**
     * Get HTML wrapper for disabled text.
     *
     * @param  string $text
     * @return string
     */
    protected function getDisabledTextWrapper($text)
    {
        return '<li class="disabled hide"><span>' . $text . '</span></li>';
    }

    /**
     * Get HTML wrapper for active text.
     *
     * @param  string $text
     * @return string
     */
    protected function getActivePageWrapper($text)
    {
        return '<li class="active"><span>' . $text . '</span></li>';
    }

    /**
     * Get a pagination "dot" element.
     *
     * @return string
     */
    protected function getDots()
    {
        return $this->getDisabledTextWrapper('...');
    }

    /**
     * Get the current page from the paginator.
     *
     * @return int
     */
    protected function currentPage()
    {
        return $this->paginator->currentPage();
    }

    /**
     * Get the last page from the paginator.
     *
     * @return int
     */
    protected function lastPage()
    {
        return $this->paginator->lastPage();
    }

}

就這麼簡單,主要就是render()方法,若是項目中須要修改分頁樣式,或者添加分頁跳轉之類的需求只要重寫其中的各項顯示的方法中的html元素就能夠了,很靈活,在blade模板中也須要修該,好比咱們的Paginator$users,默認的分頁顯示是這樣的:code

{!! $users->render() !!}

修改爲咱們自定義後的分頁顯示:

{!! with(new \App\Foundations\Pagination\CustomerPresenter($categories))->render() !!}

好了,這樣在頁面應該就能夠看到分頁連接中含有 "上一頁"和"下一頁"加數字的樣式了。

那麼若是擴展simplePaginate?其實很簡單,只要繼承剛纔的CustomerPresenter,實現hasPagesrender,至於爲何能夠按照我上面查看源碼的方式看一下就知道了,好比咱們改爲"上一篇"和"下一篇"

新建AppFoundationsPaginationCustomerSimplePresenter.php

<?php
namespace App\Foundations\Pagination;


use Illuminate\Support\HtmlString;
use Illuminate\Contracts\Pagination\Paginator as PaginatorContract;

class CustomerSimplePresenter extends CustomerPresenter
{
    /**
     * Create a simple Bootstrap 3 presenter.
     *
     * @param  \Illuminate\Contracts\Pagination\Paginator $paginator
     * @return void
     */
    public function __construct(PaginatorContract $paginator)
    {
        $this->paginator = $paginator;
    }

    /**
     * Determine if the underlying paginator being presented has pages to show.
     *
     * @return bool
     */
    public function hasPages()
    {
        return $this->paginator->hasPages() && count($this->paginator->items()) > 0;
    }

    /**
     * Convert the URL window into Bootstrap HTML.
     *
     * @return \Illuminate\Support\HtmlString
     */
    public function render()
    {
        if ($this->hasPages()) {
            return new HtmlString(sprintf(
                '<ul class="pager">%s %s</ul>',
                $this->getPreviousButton('上一篇'),
                $this->getNextButton('下一篇')
            ));
        }

        return '';
    }

}

分頁顯示:

{!! with(new \App\Foundations\Pagination\CustomerSimplePresenter($categories))->render() !!}

方法就是這個方法,具體修改按照本身需求重寫其中對應的顯示html元素的方法就能夠了。

若是以爲本篇文章對您十分有益,何不 打賞一下

謝謝打賞

謝謝打賞

相關文章
相關標籤/搜索