如何用PAGINATION CakePhp 2.x查询/查找结果?

时间:2014-05-15 09:03:46

标签: php cakephp caching pagination

我在CakePhp中使用Cache::read()Cache::write()来缓存查询。

如何更新paginator params或CACHE整个分页器?

缓存查询结果很容易但是如何缓存$this->Paginator->params()呢?

我已尝试Cache::write() $this->Paginator->params()但是如何在缓存后修改$this->Paginator->params()?当我这样做时: ...

$this->Paginator->params['paging'][$model] = $paginator_params;

... 我已经注意到了:

Indirect modification of overloaded element of CakeRequest has no effect

我何时何地可以重写PAGINATOR params / set cached params?

感谢。

2 个答案:

答案 0 :(得分:5)

您需要缓存$this->request->params['paging']数组。

你必须将Paginator Helper添加到$helpers数组。如果你不这样做,那么调用Paginator帮助器的beforeRender方法就不会被调用,并且分页链接将被破坏。

$page = !isset($this->request->named['page']) ? '1' : $this->request->named['page'];
$products = Cache::read('my_unique_cache_id_' . $page, 'query');  
$paging = Cache::read('my_unique_cache_id_paging_' . $page, 'query');

if ($products && $paging) {
    $this->set('products', $products);
    $this->request->params['paging'] = $paging;

}else{
    $products = $this->paginate('Product');
    Cache::write('my_unique_cache_id_paging_' . $page, $this->request->params['paging'], 'query');
    Cache::write('my_unique_cache_id_' . $page, $products, 'query');
    $this->set('products', $products);
}

答案 1 :(得分:1)

如果有人来这里寻找CakePHP 2.5+版本,以下应该可以正常工作,使用Cache :: remember:

list($products, $this->request->params['paging']) = Cache::remember('somestring', function() {
    return [$this->paginate('Articles'), $this->request->params['paging']];
});

您将拥有一个数组$ products,您可以将其设置到视图中进行渲染。