PaginatorHelper 在 CakePHP 4 中的使用

问题描述 投票:0回答:1

我正在将我的项目从 CakePHP 3 迁移到 4,并且我之前使用的 Paginator 组件 已被弃用。 以下是它们已被替换的内容:PaginationPaginatorHelper

我该如何访问控制器中的

PaginatorHelper
? 我无法在视图中使用它,因为我的控制器用于 API,它返回 JSON 响应(所以我没有模板)。 我需要访问
total
上的
PaginatorHelper
方法来公开 JSON 响应中的值,以使客户端能够正确处理分页。

但是,我无法在控制器中正确实例化

PaginatorHelper
。 这是我迄今为止尝试过的:

class ApiController extends AppController
{
    public function initialize(): void
    {
        parent::initialize();

        $this->viewBuilder()
            ->addHelper('Paginator')
            ->setClassName('Json');
    }

    public function list(int $limit = 10, int $page = 1)
    {
        $query = $this->People->find('visible')
            ->order(['lastname' => 'ASC']);

        $paginateSettings = [
            'limit' => $limit,
            'page' => $page,
            'maxLimit' => 100
        ];

        $this->set('people', $this->paginate($query, $paginateSettings));

        $this->set('page', $page);
        $this->set('pages', $this->Paginator->total());

        $this->viewBuilder()
            ->setOption('serialize', ['people', 'page', 'pages']);
    }
}

我还尝试将

addHelper()
调用移至
beforeRender()
而不是
initialize()
,但这并没有改变任何内容:

    public function beforeRender(EventInterface $event)
    {
        parent::beforeRender($event);

        $this->viewBuilder()
            ->addHelper('Paginator');
    }

但是我总是遇到错误

Notice: Undefined property: ApiController::$Paginator
Uncaught exception 'Error' with message 'Call to a member function total() on null'

我认为我正在按照 helpers 文档 做所有事情。那么这里有什么问题呢?

php cakephp pagination cakephp-4.x
1个回答
0
投票

最后发现不需要使用控制器中的

PaginatorHelper
来访问那些分页参数。

正如这里提到的,

您可以在

$this->request->getAttribute('paging')
访问分页元数据。

此方法返回的数组包含所有需要的参数:

[
    'People' => [
        'count' => (int) 28,
        'current' => (int) 28,
        'perPage' => (int) 30,
        'page' => (int) 1,
        'requestedPage' => (int) 1,
        'pageCount' => (int) 1,
        'start' => (int) 1,
        'end' => (int) 28,
        'prevPage' => false,
        'nextPage' => false,
        'sort' => null,
        'direction' => null,
        'sortDefault' => false,
        'directionDefault' => false,
        'completeSort' => [ ],
        'limit' => null,
        'scope' => null,
        'finder' => 'all',
    ],
]
© www.soinside.com 2019 - 2024. All rights reserved.