Created
October 28, 2014 19:48
-
-
Save eberfreitas/d80e906ddf5b9c67ab84 to your computer and use it in GitHub Desktop.
CakePHP cache with dynamic groups
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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