hyperf 分頁器


安裝

composer require hyperf/paginator

paginator控制器 app/Controller/PaginatorController.php

<?php

namespace App\Controller;

use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Paginator\Paginator;
use Hyperf\Utils\Collection;

/**
 * @AutoController()
 */
class PaginatorController
{
        public function index(RequestInterface $request)
        {
                var_dump($request);
                $currentPage = (int) $request->query('page', 1);
                $perPage = (int) $request->query('per_page', 2);

                //數據集
                $collection = new Collection([
                        ['id' => 1, 'name' => '張三'],
                        ['id' => 2, 'name' => '李四'],
                        ['id' => 3, 'name' => '小紅'],
                        ['id' => 4, 'name' => '王五'],
                        ['id' => 5, 'name' => '小明'],
                        ['id' => 6, 'name' => '小軍'],
                        ['id' => 7, 'name' => '小麗'],
                ]);

                $users = array_values($collection->forPage($currentPage, $perPage)->toArray());

                return new Paginator($users,$perPage, $currentPage);

                //$paginator = new Paginator($users, $perPage, $currentPage);
                //獲取當前頁數
                //$currentPage = $paginator->currentPage();
                //獲取當前頁的條數
                //$count = $paginator->count();
                //獲取當前頁中第一條數據的編號
                //$firstItem = $paginator->firstItem();
                //獲取當前頁中最后一條數據的編號
                //$lastItem = $paginator->lastItem();
                // 下一頁的 URL
                //$nextUrl = $paginator->nextPageUrl();
                // 上一頁的 URL
                //$previousPageUrl = $paginator->previousPageUrl();
                // 獲取指定 $page 頁數的 URL $page
                //$url = $paginator->url($currentPage+1);
                //return [
                //      'current_page'=>$currentPage,
                //      'count'=>$count,
                //      'first_item'=>$firstItem,
                //      'last_item'=>$lastItem,
                //      'next_url'=>$nextUrl,
                //      'previous_url'=>$previousPageUrl,
                //      'url'=>$url,
                //];
        }
}

訪問測試

curl 118.195.173.53:9501/paginator/index?page=2\&per_page=2

結果顯示

{
    "current_page": 2,
    "data": [{
        "id": 3,
        "name": "小紅"
    }, {
        "id": 4,
        "name": "王五"
    }],
    "first_page_url": "\/?page=1",
    "from": 3,
    "next_page_url": null,
    "path": "\/",
    "per_page": 2,
    "prev_page_url": "\/?page=1",
    "to": 4
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM