Skip to content

Instantly share code, notes, and snippets.

@eberfreitas
Created October 28, 2014 19:48
Show Gist options
  • Save eberfreitas/d80e906ddf5b9c67ab84 to your computer and use it in GitHub Desktop.
Save eberfreitas/d80e906ddf5b9c67ab84 to your computer and use it in GitHub Desktop.
CakePHP cache with dynamic groups
<?php
App::uses('Cache', 'Cache');
class PowerCache {
public static function write($key, $value, $config = 'default', $groups = []) {
if (!empty($groups)) {
$groups = !is_array($groups) ? [$groups] : $groups;
$groupsConfig = !empty(Configure::read('powercache.config'))
? Configure::read('powercache.config')
: 'default';
$groupsPrefix = !empty(Configure::read('powercache.prefix'))
? Configure::read('powercache.prefix')
: 'pc_';
foreach ($groups as $group) {
$groupKeys = Cache::read($groupsPrefix . $group, $groupsConfig);
$groupKey = $key . '|' . $config;
if (!$groupKeys) {
$groupKeys = [];
}
if (!in_array($groupKey, $groupKeys)) {
$groupKeys[] = $groupKey;
Cache::write($groupsPrefix . $group, $groupKeys, $groupsConfig);
}
}
}
return Cache::write($key, $value, $config);
}
public static function clearGroup($groups = [], $config = 'default') {
$groups = !is_array($groups) ? [$groups] : $groups;
$groupsConfig = !empty(Configure::read('powercache.config'))
? Configure::read('powercache.config')
: 'default';
$groupsPrefix = !empty(Configure::read('powercache.prefix'))
? Configure::read('powercache.prefix')
: 'pc_';
foreach ($groups as $group) {
$keys = Cache::read($groupsPrefix . $group, $groupsConfig);
if (!empty($keys)) {
foreach ($keys as $key) {
list($key, $config) = explode('|', $key);
Cache::delete($key, $config);
}
}
}
}
public static function read($key, $config = 'default') {
return Cache::read($key, $config);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment