Skip to content

Instantly share code, notes, and snippets.

@squallstar
Last active June 11, 2018 16:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save squallstar/9093354 to your computer and use it in GitHub Desktop.
Save squallstar/9093354 to your computer and use it in GitHub Desktop.
PHP Cache like Rails.cache.fetch
<?php
/**
* PHP Cache class inspired by Rails.cache.fetch
*
* @author Nicholas Valbusa - @squallstar
* @copyright Copyright (c) 2014, Nicholas Valbusa
* @license GNU/GPL (General Public License)
* @link https://gist.github.com/squallstar/9093354
*
*/
class Cache
{
// Make sure this directory exists
const CACHE_PATH = 'tmp/';
// Invalidate the cache by changing the version
const CACHE_VERSION = '1';
public static function fetch ($key = '', $callback)
{
$path = self::CACHE_PATH . self::CACHE_VERSION . $key . '.tmp';
if (file_exists($path)) return unserialize(file_get_contents($path));
try
{
$result = $callback(true);
}
catch (Exception $e)
{
var_dump($e);
die;
}
if ($result === null) return $result;
file_put_contents($path, serialize($result));
return $result;
}
}

PHP Cache inspired by Rails cache

In Rails, you can do:

articles = Rails.cache.fetch "blog-articles" do
  BlogArticles.all
end

Therefore I created a simple class for my tiny PHP projects that will basically do the same. First of all, require the class:

<?php require_once 'cache.php';

And create a folder named tmp. Note that you can change it by updating the CACHE_PATH constant on the cache class.

Then, in a similar way you can do:

$articles = Cache::fetch("blog-articles", function() {
  return mysql_query("select * from blog_articles;");
});

The return can be any kind of object, since it will be serialized using PHP's built-in functions.


A nice way to use it in a real app is the following:

$user_projects = Cache::fetch("user-projects-" . $user->updated_at, function() {
  return mysql_query("select * from projects where user_id = $user->id;");
});

In the example above, anytime you will update the $user.updated_at timestamp, the cache will be invalidated.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment