How to CACHE query/find results with PAGINATION Ca

2019-04-17 07:05发布

I use Cache::read(), Cache::write() in CakePhp to cache queries.

How to update paginator params or CACHE whole paginator?

It easy to cache query result but how to cache $this->Paginator->params() too?

I've tried to Cache::write() $this->Paginator->params() but how to modify $this->Paginator->params() after caching? When I do someting like: ...

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

... I've got notice:

Indirect modification of overloaded element of CakeRequest has no effect

Where and when I can rewrite PAGINATOR params/set cached params?

Thanks.

2条回答
Fickle 薄情
2楼-- · 2019-04-17 07:24

You need to cache $this->request->params['paging'] array.

And you have to add Paginator Helper to $helpers array. If you don't, beforeRender method of Paginator helper won't be invoked and paging links will be broken.

$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);
}
查看更多
我想做一个坏孩纸
3楼-- · 2019-04-17 07:35

If anyone's come here looking for a CakePHP 2.5+ version of this, the following should work well, using Cache::remember:

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

You'll have an array, $products, which you can set onto your view for rendering.

查看更多
登录 后发表回答