Skip to content

Instantly share code, notes, and snippets.

@demogar
Created October 4, 2011 15:59
Show Gist options
  • Select an option

  • Save demogar/1262015 to your computer and use it in GitHub Desktop.

Select an option

Save demogar/1262015 to your computer and use it in GitHub Desktop.
Pgache
<?php
/**
* Pgcache is a library used for caching elements using the built-in cache driver
*
* @author Demostenes Garcia <me@demogar.com>
*/
class Pgcache
{
// CI Object
protected $ci;
/**
* Constructor, get the instance of codeigniter's singleton object
*/
function __construct()
{
$this->ci =& get_instance();
$this->ci->load->driver('cache', array('adapter' => 'file'));
log_message('debug', "Pgcache initialized");
}
/**
* Generate the name for the cache file. Internally used
*
* @param prefix
* @param class
* @param method
* @param params
*/
private function _generate_name($prefix, $class, $method, $params)
{
return $class . "_" . $prefix . "_" . $method . "_" . str_replace( ",", "_", implode($params) );
}
/**
* Method that caches a model call result
*
* @param model
* @param method
* @param params
* @param expires
*/
public function model($model, $method, $params = array(), $expires = NULL)
{
$this->ci->load->model($model);
if (! is_array($params)) $params = (array) $params;
$params = array_values($params);
$cache_name = $this->_generate_name( "m", $model, $method, $params );
$item = $this->ci->cache->get($cache_name);
if ($item)
{
return unserialize($item);
}
else
{
$item = call_user_func_array( array($this->ci->$model, $method), $params );
$this->ci->cache->save( $cache_name, serialize($item), $expires );
return $item;
}
}
}
/* End of file: Pgcache.php */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment