Skip to content

Instantly share code, notes, and snippets.

@sdemontfort
Last active August 29, 2015 14:06
Show Gist options
  • Save sdemontfort/c7f4d7213d27f2d7576b to your computer and use it in GitHub Desktop.
Save sdemontfort/c7f4d7213d27f2d7576b to your computer and use it in GitHub Desktop.
Laravel 3 Eloquent single object caching
<?php
/**
* Override eloquent to provide caching on single objects.
* Note: This will cache items forever, and will create new cache files
* upon updates, so that the latest cache item will always be used.
* The goal is to move towards this approach:
* https://signalvnoise.com/posts/3113-how-key-based-cache-expiration-works
*
* P.S this should be used with Memcached
*/
class Base extends Eloquent {
private function getModelName()
{
return strtolower(get_class($this));
}
public function save(array $options = array())
{
parent::save($options);
if (static::$cacheable)
{
$model_name = $this->getModelName();
$cache_timestamp = strtotime($this->updated_at);
Cache::forever($model_name . '-' . $this->id . '-timestamp', $cache_timestamp);
Cache::forever($model_name . '-' . $this->id . '-' . $cache_timestamp, $this);
}
}
public function find($id)
{
$model_name = $this->getModelName();
$cache_key = $model_name . '-' . $id . '-timestamp';
if (Cache::has($cache_key))
{
$timestamp = Cache::get($cache_key);
return Cache::get($model_name . '-' . $id . '-' . $timestamp);
}
return parent::find($id);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment