Skip to content

Instantly share code, notes, and snippets.

@alexander-torosh
Created November 19, 2015 12:27
Show Gist options
  • Select an option

  • Save alexander-torosh/c7eb71d305fc4c71600d to your computer and use it in GitHub Desktop.

Select an option

Save alexander-torosh/c7eb71d305fc4c71600d to your computer and use it in GitHub Desktop.
Phalcon CacheManager Helper
<?php
// ...
$di->set('cacheManager', new CacheManager());
<?php
/**
* @author Oleksandr Torosh <[email protected]>
* @property \Phalcon\Cache\Backend\File $cache
*/
namespace Demio\Cache;
use Phalcon\Mvc\User\Component;
class Manager extends Component
{
/**
* Get cache data. If data not exists, generate data and save to cache
*/
public function load($key, $closure, $lifetime = 60)
{
if ($lifetime == 0) {
return $closure();
}
$data = $this->cache->get($key, $lifetime);
if (!$data) {
$data = $closure();
$this->cache->save($key, $data, $lifetime);
}
return $data;
}
public function save($key, $data, $lifetime)
{
$this->cache->save($key, $data, $lifetime);
}
public function key(array $params = [])
{
return md5(serialize($params));
}
public function delete($key)
{
$this->cache->delete($key);
}
}
<?php
// $param1, $param2 ...
// Cache Key
$key = $this->cacheManager([
'entityName',
$param1,
$param2
]);
// Cache Usage
$result = $this->cacheManager($key, function() use ($param1, $param2){
// Any Logics ...
$qb = $this->modelsManager->createBuilder()
->addFrom('/* ... */')
->where('/* ... */');
$result = $qb->getQuery()->execute();
return $result;
}, 60);
// Cache Delete
$this->cacheManager->delete($key);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment