Home

Awesome

CakePHP API Pagination

Latest Version on Packagist Software License Build Status Coverage Status Quality Score Total Downloads

This is a simple component for CakePHP 4.2+ which injects pagination information from CakePHP's Paginator into serialized JsonView and XmlView responses.

See 1.x and 2.x releases and branches of this plugin for support of previous versions of CakePHP before 4.2.

Install

Via Composer

$ composer require bcrowe/cakephp-api-pagination

Load the plugin by adding $this->addPlugin('BryanCrowe/ApiPagination'); to the bootsrap method in your project’s src/Application.php:

public function bootstrap(): void
{
    parent::bootstrap();
    
    // ... bootstrap code ...

    // load more plugins here
    
    $this->addPlugin('BryanCrowe/ApiPagination');
}

Usage

Make sure your application has been set up to use data views; see the Enabling Data Views in Your Application section of the CakePHP documentation.

Then, load ApiPaginationComponent:

$this->loadComponent('BryanCrowe/ApiPagination.ApiPagination');

Then, go ahead and set your paginated view variable like so:

$this->set('articles', $this->paginate($this->Articles));
$this->viewBuilder()->setOption('serialize', ['articles']);

Note: It is important that your serialize option is an array, e.g. ['articles'], so that your pagination information can be set under its own pagination key.

Your JsonView and XmlView responses will now contain the pagination information, and will look something like this:

{
    "articles": ["...", "...", "..."],
    "pagination": {
        "finder": "all",
        "page": 1,
        "current": 20,
        "count": 5000,
        "perPage": 20,
        "prevPage": false,
        "nextPage": true,
        "pageCount": 250,
        "sort": null,
        "direction": false,
        "limit": null,
        "sortDefault": false,
        "directionDefault": false
    }
}

Configuring the Pagination Output

ApiPagination has four keys for configuration: key, aliases, visible and model.

An example using all these configuration keys:

$this->loadComponent('BryanCrowe/ApiPagination.ApiPagination', [
    'key' => 'paging',
    'aliases' => [
        'page' => 'currentPage',
        'current' => 'resultCount'
    ],
    'visible' => [
        'currentPage',
        'resultCount',
        'prevPage',
        'nextPage'
    ],
    'model' => 'Articles',
]);

This configuration would yield:

{
    "articles": ["...", "...", "..."],
    "paging": {
        "prevPage": false,
        "nextPage": true,
        "currentPage": 1,
        "resultCount": 20
    }
}

Changelog

Please see CHANGELOG for more information what has changed recently.

Testing

$ composer test

Contributing

Please see CONTRIBUTING and CONDUCT for details.

Security

If you discover any security related issues, please email bryan@bryan-crowe.com instead of using the issue tracker.

Credits

License

The MIT License (MIT). Please see License File for more information.