I've used your suggestion for the Adapter, so I've extended the File adpter (i need it, no more) using that flag to return false.
Than I've created a cache manager in order to manage the cache logic inside a class and not inside the controllers or the methods.
class CacheManager extends Component
{
/**
* Get cache data. If data not exists, generate data and save to cache
*/
public function get($key, $closure, $lifetime = 3000, $prefix = null)
{
//if array, serialize it and get unique key, altough use the string $key
if (is_array($key)) {
$key = $this->key($key);
}
//the prefix is useful to group several serialized keys
if ($prefix) {
$key = $prefix . "-" . $key;
}
if ($lifetime == 0) {
return $closure();
}
$data = $this->cache->get($key, $lifetime);
if (!$data) {
$data = $closure();
// if cache is disabled skip this step
if ($this->getDi()->get('config')->cache->active) {
$this->cache->save($key, $data, $lifetime);
}
}
return $data;
}
public function save($key, $data, $lifetime)
{
if (is_array($key)) {
$key = $this->key($key);
}
$this->cache->save($key, $data, $lifetime);
}
public function delete($key)
{
if (is_array($key)) {
$key = $this->key($key);
}
$this->cache->delete($key);
}
public function key(array $params = [])
{
return md5(json_encode($params));
}
}
inside config.ini I have a cache section, of course.
So to use cache for a peace of code, or a method, you have just to put it inside the closure. I think that way to manage cache is usefull for large resultsets and their manipulation. I've not considered the possibility to use ORM persistent cache, but you can achieve it in this way
public static function find($parameters = null)
{
// Convert the parameters to an array
if (!is_array($parameters)) {
$parameters = [$parameters];
}
return \Phalcon\DI::getDefault()->get('cacheManager')->get(
$parameters,
function () use ($parameters) {
return parent::find($parameters);
}
);
}