cakephp mysql query pagination caching

To implement pagination caching in CakePHP, add the below code in your app_model.php file.

function paginate ($conditions, $fields, $order, $limit, $page = 1, $recursive = null, $extra = array())
{
$args = func_get_args();
$uniqueCacheId = ”;
foreach ($args as $arg) {
$uniqueCacheId .= serialize($arg);
}
if (!empty($extra[‘contain’])) {
$contain = $extra[‘contain’];
}
$uniqueCacheId = md5($uniqueCacheId);
$pagination = Cache::read(‘pagination-‘.$this->alias.’-‘.$uniqueCacheId, ‘paginate_cache’);
if (empty($pagination)) {
$pagination = $this->find(‘all’, compact(‘conditions’, ‘fields’, ‘order’, ‘limit’, ‘page’, ‘recursive’, ‘group’, ‘contain’));
Cache::write(‘pagination-‘.$this->alias.’-‘.$uniqueCacheId, $pagination, ‘paginate_cache’);
}
return $pagination;
}

function paginateCount ($conditions = null, $recursive = 0, $extra = array()) {
$args = func_get_args();
$uniqueCacheId = ”;
foreach ($args as $arg) {
$uniqueCacheId .= serialize($arg);
}
$uniqueCacheId = md5($uniqueCacheId);
if (!empty($extra[‘contain’])) {
$contain = $extra[‘contain’];
}

$paginationcount = Cache::read(‘paginationcount-‘.$this->alias.’-‘.$uniqueCacheId, ‘paginate_cache’);
if (empty($paginationcount)) {
$paginationcount = $this->find(‘count’, compact(‘conditions’, ‘contain’, ‘recursive’));
Cache::write(‘paginationcount-‘.$this->alias.’-‘.$uniqueCacheId, $paginationcount, ‘paginate_cache’);
}
return $paginationcount;
}

You need to specify the caching rule in core.php, something like:

Cache::config(‘paginate_cache’, array(
‘engine’        => ‘File’,
‘path’      => CACHE .’sql’. DS,
‘serialize’ => true,
‘duration’ => ‘+1 hour’,
));

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s