phlacon分页的layui样式实现

原创文章,欢迎转载:http://miao.blog/article/phalcon-paginator-layui-adapter

博客样式整体基于layui,本来layui包含分页组件,但是前端分页组件不适用于博客系统,
所以抽空把MIAO.BLOG的后端分页功能实现了,记录一下实现过程

phalcon本身自带分页功能,但是提供的样式比较简单,并且查询了全部记录,并不科学。

// 后端代码
<?php

use Phalcon\Paginator\Adapter\Model as PaginatorModel;

// Current page to show
// In a controller this can be:
// $this->request->getQuery('page', 'int'); // GET
// $this->request->getPost('page', 'int'); // POST
$currentPage = (int) $_GET["page"];

// The data set to paginate
$robots      = Robots::find();

// Create a Model paginator, show 10 rows by page starting from $currentPage
$paginator   = new PaginatorModel(
    array(
        "data"  => $robots,
        "limit" => 10,
        "page"  => $currentPage
    )
);

// Get the paginated results
$page = $paginator->getPaginate();

// 前端代码
<a href="/robots/search">First</a>
<a href="/robots/search?page=<?= $page->before; ?>">Previous</a>
<a href="/robots/search?page=<?= $page->next; ?>">Next</a>
<a href="/robots/search?page=<?= $page->last; ?>">Last</a>


比较方便的是,phalcon提供了实现自定义分页适配器的方式来实现分页

<?php
namespace Miao\Common;

use Phalcon\Paginator\AdapterInterface as PaginatorInterface;

class MiaoPaginator implements PaginatorInterface
{
    /**
     * @var string base url
     */
    private $baseUrl;

    /**
     * @var int page size
     */
    private $limit;

    /**
     * @var int current page
     */
    private $page;

    /**
     * @var int total record count
     */
    private $totalCount;

    /**
     * @var int page count
     */
    private $pageCount;

    /**
     * @var string first page
     */
    private $first = "";

    /**
     * @var string last page
     */
    private $last = "";

    /**
     * @var string items
     */
    private $items = "";

    /**
     * @var string next page
     */
    private $next = "";

    /**
     * @var string prev page
     */
    private $prev = "";

    /**
     * Adapter constructor
     *
     * @param array $config
     */
    public function __construct($config)
    {
        $this->baseUrl = $config['baseUrl'];
        $this->limit = $config['limit'];
        $this->page = $config['page'];
        $this->totalCount = $config['totalCount'];
        $this->pageCount = ceil($this->totalCount / $this->limit);
    }

    /**
     * Set the current page number
     *
     * @param int $page
     */
    public function setCurrentPage($page)
    {
        $this->page = $page;
    }

    /**
     * Returns a slice of the resultset to show in the pagination
     *
     * @return string
     */
    public function getPaginate()
    {
        // return empty when only 1 page
        if ($this->pageCount == 1)
            return "";

        // prev page
        if ($this->page > 1) {
            $prevPage = $this->page - 1;
            $this->prev = "<a class=\"layui-laypage-prev\" title=\"上一页\" href=\"/{$this->baseUrl}?page={$prevPage}\">上一页</a>";
        }

        // next page
        if ($this->page < $this->pageCount) {
            $lastPage = $this->page + 1;
            $this->next = "<a class=\"layui-laypage-next\" title=\"下一页\" href=\"/{$this->baseUrl}?page={$lastPage}\">下一页</a>";
        }

        // page index
        $pageIndex = [];
        if ($this->pageCount <= 5) {
            for ($i = 1; $i <= $this->pageCount; $i++) {
                $pageIndex[] = $i;
            }
        } else {
            if ($this->page < 5) {
                $pageIndex = [1, 2, 3, 4, 5, "...", $this->pageCount];
            } elseif ($this->page < $this->pageCount - 2) {
                $pageIndex = [
                    1,
                    "...",
                    $this->page - 2, $this->page - 1, $this->page, $this->page + 1, $this->page + 2,
                    "...",
                    $this->pageCount
                ];
            } else {
                $pageIndex = [
                    1,
                    "...",
                    $this->pageCount - 4, $this->pageCount - 3, $this->pageCount - 2, $this->pageCount - 1,
                    $this->pageCount
                ];
            }
        }

        // items
        foreach ($pageIndex as $idx) {
            if ($idx == $this->page) {
                $item = "<span class=\"layui-laypage-curr\"><em class=\"layui-laypage-em\"></em><em>${idx}</em></span>";
            } elseif ($idx == "...") {
                $item = "<span>…</span>";
            } else {
                // title
                if ($idx == 1) {
                    $title = "title=\"首页\"";
                } elseif ($idx == $this->pageCount) {
                    $title = "title=\"末页\"";
                } else {
                    $title = "";
                }
                $item = "<a href=\" /{$this->baseUrl}?page={$idx}\" {$title}>{$idx}</a>";
            }
            $this->items .= $item;
        }

        $pager = $this->prev . $this->first . $this->items . $this->last . $this->next;
        return "<div class='layui-box layui-laypage layui-laypage-molv'>{$pager}</div>";
    }

    /**
     * Set current rows limit
     *
     * @param int $limit
     */
    public function setLimit($limit)
    {
        $this->limit = $limit;
    }

    /**
     * Get current rows limit
     *
     * @return int
     */
    public function getLimit()
    {
        return $this->limit;
    }
}


然后调用代码
后端action

public function indexAction()
    {
        // 当前页
        $page = empty($_GET['page']) ? 1 : $_GET['page'];

        // limit
        $limit = isset($pager->limit_front) ? $pager->limit_front : 15;
        $offset = $limit * ($page - 1);

        // 分页查询文章列表
        $this->view->articles = Article::find(
            [
                'limit' => $limit,
                'offset' => $offset
            ]
        );

        $this->view->pager = $this->getPager($limit, $page);
    }

    /**
     * @param $limit
     * @param $page
     * @return string
     */
    private function getPager($limit, $page)
    {

        // 总记录数
        $totalCount = Article::count();

        // 分页
        $paginator = new MiaoPaginator(
            [
                'baseUrl' => '',
                'limit' => $limit,
                'page' => $page,
                'totalCount' => $totalCount
            ]
        );
        return $paginator->getPaginate();
    }

前端代码

<div>{{ pager }}</div>

然后效果
分页效果

推荐阅读
自 PHP 5.4.0 起,可以使用Traits在类中复用代码。关于Trait的详细介绍看 这里 。用Trait实现model插入数据时自动记录created_at, 更新数据时自动更新updated_at:
下边步骤是php已经安装好的前提下的操作: 环境:centos6.4 + php5.6.22 + nginx1.10.0。 步骤: git clone https://github.com/phalcon/cphalcon cd cphalcon/build/php5/64bits make clean /usr/local/php/bin/phpize --clean /usr/local/php/bin/phpize ./configure --with-php-config=/usr/local/p
评论