Caching of simple queries against primary key.

This commit is contained in:
Josh Sherman 2011-10-30 20:49:23 -04:00
parent 4b96d28bb7
commit e104250597
4 changed files with 120 additions and 18 deletions

View file

@ -42,6 +42,14 @@ class Model extends Object
*/
protected $cache = null;
/**
* Whether or not to use cache
*
* @access protected
* @var boolean
*/
protected $use_cache = false;
/**
* SQL Array
*
@ -249,8 +257,14 @@ class Model extends Object
parent::__construct();
// Gets an instance of the cache and database
$this->db = Database::getInstance($this->datasource != '' ? $this->datasource : null);
$this->cache = Cache::getInstance();
// @todo Datasource has no way of being set
$this->db = Database::getInstance($this->datasource != '' ? $this->datasource : null);
$this->caching = $this->db->getCache();
if ($this->caching)
{
$this->cache = Cache::getInstance();
}
// Builds out the query
if ($type_or_parameters != null)
@ -272,6 +286,7 @@ class Model extends Object
elseif (ctype_digit((string)$type_or_parameters))
{
$this->loadParameters(array($this->id => $type_or_parameters));
$cache_key = sha1('PICKLES-' . $this->datasource . '-' . $this->table . '-' . $type_or_parameters);
}
elseif (ctype_digit((string)$parameters))
{
@ -310,7 +325,26 @@ class Model extends Object
break;
}
$this->records = $this->db->fetch(implode(' ', $this->sql), (count($this->input_parameters) == 0 ? null : $this->input_parameters));
$query_database = true;
if (isset($cache_key))
{
$cached = $this->cache->get($cache_key);
}
if (isset($cached) && $cached)
{
$this->records = $cached;
}
else
{
$this->records = $this->db->fetch(implode(' ', $this->sql), (count($this->input_parameters) == 0 ? null : $this->input_parameters));
if (isset($cache_key))
{
$this->cache->set($cache_key, $this->records);
}
}
}
else
{
@ -919,6 +953,11 @@ class Model extends Object
{
$sql .= ' WHERE ' . $this->id . ' = :' . $this->id . ' LIMIT 1;';
$input_parameters[':' . $this->id] = $this->record[$this->id];
if ($this->caching)
{
$this->cache->delete(sha1('PICKLES-' . $this->datasource . '-' . $this->table . '-' . $this->record[$this->id]));
}
}
// Executes the query