如何在cakephp2 Paginator组件中获取未发现异常


How to fetch the Not Found Exception in cakePHP 2 Paginator Component

我使用Paginator Component,每当用户/bot转到高页码时,他将得到Not Found Exception。这可能很好,但我想用301重定向用户回到第一页。

现在我知道[cakePHP 2文档][1]告诉我如何为个别情况做到这一点,但我想为所有分页做到这一点,而不是每次都添加代码位。

我试图在我的应用程序中构建我自己的Paginator组件,与核心组件作为父组件,但由于我没有名称空间,我只是调用我自己的组件并以循环结束

    <?php
    App::uses('PaginatorComponent', 'Vendor/Controller/Component');
    class PaginatorComponent extends PaginatorComponent {
        public function paginate($object = null, $scope = array(), $whitelist = array()) {
            try {
                PaginatorComponent::paginate($object, $scope, $whitelist);
            } catch (NotFoundException $e) {
                if ($this->request->query('page') <= 1) {
                    throw new NotFoundException();
                }
                $this->redirect($this->here);
            }
        }
    }

您不能将组件命名为PaginatorComponent,因为它已经存在!这一行应该会立即敲响警钟:-

class PaginatorComponent extends PaginatorComponent {

将组件命名为不同的名称,如CustomPaginatorComponent:-

class CustomPaginatorComponent extends PaginatorComponent {

您还需要在您的自定义paginate()方法中调用parent::paginate(),而不是PaginatorComponent::paginate()