承接 lampager/lampager-cakephp 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

lampager/lampager-cakephp

Composer 安装命令:

composer require lampager/lampager-cakephp

包简介

Rapid pagination for CakePHP 5

README 文档

README

lampager-cakephp

CI Workflow Coverage Status Scrutinizer Code Quality

Lampager for CakePHP

Rapid pagination without using OFFSET

Requirements

Note

Installing

composer require lampager/lampager-cakephp:^3.0

For SQLite users, see SQLite to configure.

Basic Usage

Simply install as a Composer package and use in one or more of the following methods:

  • Use in Controller (via \Lampager\Cake\Datasource\Paginator)
  • Use in Table (via \Lampager\Cake\Model\Behavior\LampagerBehavior)

Use in Controller

At first, configure $paginate to use \Lampager\Cake\Datasource\Paginator in your Controller class.

namespace App\Controller;

use Cake\Controller\Controller;
use Lampager\Cake\Datasource\Paginator;

class AppController extends Controller
{
    public $paginate = [
        'className' => Paginator::class,
    ];
}

Use in a way described in the Cookbook: Pagination. Note the options that are specific to Lampager such as forward, seekable, or cursor.

$query = $this->Posts
    ->where(['Posts.type' => 'public'])
    ->orderByDesc('created')
    ->orderByDesc('id')
    ->limit(10);

$posts = $this->paginate($query, [
    'forward' => true,
    'seekable' => true,
    'cursor' => [
        'id' => 4,
        'created' => '2020-01-01 10:00:00',
    ],
]);

$this->set('posts', $posts);

Use in Table

Initialize LampagerBehavior in your Table class (AppTable is preferable) and simply use lampager() there.

namespace App\Model\Table;

use Cake\ORM\Table;
use Lampager\Cake\Model\Behavior\LampagerBehavior;

class AppTable extends Table
{
    public function initialize(array $config): void
    {
        parent::initialize($config);

        $this->addBehavior(LampagerBehavior::class);
    }
}

The query builder (\Lampager\Cake\ORM\Query) extends the plain old \Cake\ORM\Query and is mixed in with \Lampager\Paginator. Note that some of the methods in \Lampager\Paginator, viz., orderBy(), orderByDesc(), and clearOrderBy() are not exposed because their method signatures are not compatible with the CakePHP query builder.

$cursor = [
    'id' => 4,
    'created' => '2020-01-01 10:00:00',
    'modified' => '2020-01-01 12:00:00',
];

/** @var \Lampager\Cake\PaginationResult $latest */
$latest = $this->lampager()
    ->forward()
    ->seekable()
    ->cursor($cursor)
    ->limit(10)
    ->orderByDesc('Posts.modified')
    ->orderByDesc('Posts.created')
    ->orderByDesc('Posts.id')
    ->paginate();

foreach ($latest as $post) {
    /** @var \Cake\ORM\Entity $post */
    debug($post->id);
    debug($post->created);
    debug($post->modified);
}

The methods from the CakePHP query builder, e.g., where(), are available. \Cake\Database\Expression\QueryExpression is accepted as well.

/** @var \Lampager\Cake\PaginationResult $drafts */
$drafts = $this->lampager()
    ->where(['type' => 'draft'])
    ->forward()
    ->seekable()
    ->cursor($cursor)
    ->limit(10)
    ->orderByDesc($this->selectQuery()->newExpr('modified'))
    ->orderByDesc($this->selectQuery()->newExpr('created'))
    ->orderByDesc($this->selectQuery()->newExpr('id'))
    ->paginate();

/** @var \Cake\ORM\Entity $sample */
$sample = $drafts->sample();

/** @var int $count */
$count = $drafts->count();

Classes

See also: lampager/lampager.

Name Type Parent Class
Implemented Interface
Description
Lampager\Cake\ORM\Query Class Cake\ORM\Query Fluent factory implementation for CakePHP
Lampager\Cake\Model\Behavior\LampagerBehavior Class Cake\ORM\Behavior CakePHP behavior which returns Lampager\Cake\ORM\Query
Lampager\Cake\Datasource\Paginator Class Cake\Datasource\Paginator CakePHP paginatior which delegates to Lampager\Cake\ORM\Query
Lampager\Cake\Paginator Class Lampager\Paginator Paginator implementation for CakePHP
Lampager\Cake\ArrayProcessor Class Lampager\ArrayProcessor Processor implementation for CakePHP
Lampager\Cake\PaginationResult Class Lampager\PaginationResult
Cake\Datasource\Paging\PaginatedInterface
PaginationResult implementation for CakePHP
Lampager\Cake\Database\SqliteCompiler Class Cake\Database\QueryCompiler Query compiler implementation for SQLite
Lampager\Cake\Database\Driver\Sqlite Class Cake\Database\Driver\Sqlite Driver implementation which delegates to Lampager\Cake\Database\SqliteCompiler

API

See also: lampager/lampager.

LampagerBehavior::lampager()

Build a Lampager query from Table in exactly the same way as CakePHP.

LampagerBehavior::lampager(): \Lampager\Cake\ORM\Query

Paginator::__construct()
Paginator::create()

Create a new paginator instance. These methods are not intended to be directly used in your code.

static Paginator::create(\Cake\ORM\Query\SelectQuery $builder): static
Paginator::__construct(\Cake\ORM\Query\SelectQuery $builder)

Paginator::transform()

Transform a Lampager query into a CakePHP query.

Paginator::transform(\Lampager\Query $query): \Cake\ORM\Query\SelectQuery

Paginator::build()

Perform configure + transform.

Paginator::build(\Lampager\Contracts\Cursor|array $cursor = []): \Cake\ORM\Query\SelectQuery

Paginator::paginate()

Perform configure + transform + process.

Paginator::paginate(\Lampager\Contracts\Cursor|array $cursor = []): \Lampager\Cake\PaginationResult

Arguments

  • (mixed) $cursor
    An associative array that contains $column => $value or an object that implements \Lampager\Contracts\Cursor. It must be all-or-nothing.
    • For the initial page, omit this parameter or pass an empty array.
    • For the subsequent pages, pass all the parameters. The partial one is not allowed.

Return Value

e.g.,

(Default format when using \Cake\ORM\Query)

object(Lampager\Cake\PaginationResult)#1 (6) {
  ["(help)"]=>
  string(44) "This is a Lampager Pagination Result object."
  ["records"]=>
  array(3) {
    [0]=>
    object(Cake\ORM\Entity)#2 (11) { ... }
    [1]=>
    object(Cake\ORM\Entity)#3 (11) { ... }
    [2]=>
    object(Cake\ORM\Entity)#4 (11) { ... }
  ["hasPrevious"]=>
  bool(false)
  ["previousCursor"]=>
  NULL
  ["hasNext"]=>
  bool(true)
  ["nextCursor"]=>
  array(2) {
    ["created"]=>
    object(Cake\I18n\Time)#5 (3) {
      ["date"]=>
      string(26) "2017-01-01 10:00:00.000000"
      ["timezone_type"]=>
      int(3)
      ["timezone"]=>
      string(3) "UTC"
    }
    ["id"]=>
    int(1)
  }
}

PaginationResult::__call()

\Lampager\Cake\PaginationResult implements \Cake\Datasource\Paging\PaginatedInterface.

Examples

This section describes the practical usage of lampager-cakephp.

Use in Controller

The example below shows how to accept a cursor parameter from a request and pass it through PaginatorComponent::paginate(). Be sure that your AppController has properly initialized Paginator as above.

namespace App\Controller;

class PostsController extends AppController
{
    public $Posts = null;

    /**
     * This method shows how to pass options by a query and array.
     */
    public function query(): void
    {
        // Get cursor parameters
        $previous = json_decode($this->request->getQuery('previous_cursor'), true);
        $next = json_decode($this->request->getQuery('next_cursor'), true);
        $cursor = $previous ?: $next ?: [];

        // Query expression can be passed to PaginatorComponent::paginate() as normal
        $query = $this->Posts
            ->where(['Posts.type' => 'public'])
            ->orderByDesc('created')
            ->orderByDesc('id')
            ->limit(15);

        /** @var \Lampager\Cake\PaginationResult<\Cake\ORM\Entity> $posts */
        $posts = $this->paginate($query, [
            // If the previous_cursor is not set, paginate forward; otherwise backward
            'forward' => !$previous,
            'cursor' => $cursor,
            'seekable' => true,
        ]);

        $this->set('posts', $posts);
    }

    /**
     * This method shows how to pass options from an array.
     */
    public function options(): void
    {
        // Get cursor parameters
        $previous = json_decode($this->request->getQuery('previous_cursor'), true);
        $next = json_decode($this->request->getQuery('next_cursor'), true);
        $cursor = $previous ?: $next ?: [];

        /** @var \Lampager\Cake\PaginationResult<\Cake\ORM\Entity> $posts */
        $posts = $this->paginate('Posts', [
            // Lampager options
            // If the previous_cursor is not set, paginate forward; otherwise backward
            'forward' => !$previous,
            'cursor' => $cursor,
            'seekable' => true,

            // PaginatorComponent config
            'conditions' => [
                'type' => 'public',
            ],
            'order' => [
                'created' => 'DESC',
                'id' => 'DESC',
            ],
            'limit' => 15,
        ]);

        $this->set('posts', $posts);
    }
}

And the pagination links can be output as follows:

// If there is a next page, print pagination link
if ($posts->hasPrevious) {
    echo $this->Html->link('<< Previous', [
        'controller' => 'posts',
        'action' => 'index',
        '?' => [
            'previous_cursor' => json_encode($posts->previousCursor),
        ],
    ]);
}

// If there is a next page, print pagination link
if ($posts->hasNext) {
    echo $this->Html->link('Next >>', [
        'controller' => 'posts',
        'action' => 'index',
        '?' => [
            'next_cursor' => json_encode($posts->nextCursor),
        ],
    ]);
}

Supported database engines

MySQL, MariaDB, and PostgreSQL

Supported!

Microsoft SQL Server

Not supported.

SQLite

Supported but requires an additional configuration.

In SQLite UNION ALL statements cannot combine SELECT statements that have ORDER BY clause. In order to get this to work, those SELECT statements have to be wrapped by a subquery like SELECT * FROM (...). CakePHP not natively handling this situation, Lampager for CakePHP introduces \Lampager\Cake\Database\Driver\Sqlite that needs to be installed on your application. Configure like the following in your config/app.php:

return [
    'Datasources' => [
        'default' => [
            'className' => Connection::class,
            'driver' => \Lampager\Cake\Database\Driver\Sqlite::class,
            'username' => '********',
            'password' => '********',
            'database' => '********',
        ],
    ],
];

lampager/lampager-cakephp 适用场景与选型建议

lampager/lampager-cakephp 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 31.04k 次下载、GitHub Stars 达 7, 最近一次更新时间为 2020 年 01 月 01 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「paginator」 「pagination」 「cakephp」 「limit」 「offset」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 lampager/lampager-cakephp 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 lampager/lampager-cakephp 我们能提供哪些服务?
定制开发 / 二次开发

基于 lampager/lampager-cakephp 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 31.04k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 7
  • 点击次数: 18
  • 依赖项目数: 0
  • 推荐数: 1

GitHub 信息

  • Stars: 7
  • Watchers: 8
  • Forks: 3
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2020-01-01