Skip to content

Instantly share code, notes, and snippets.

@lucasgameiro
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lucasgameiro/bf7ede00a97bd9efb643 to your computer and use it in GitHub Desktop.
Save lucasgameiro/bf7ede00a97bd9efb643 to your computer and use it in GitHub Desktop.
Simple file cache static class
<?php
define('DS', DIRECTORY_SEPARATOR);
class FileCache
{
public static $options = array(
'folder' => 'tmp',
'prefix' => 'havaianas_cache_',
'expires' => '+20 minutes'
);
public static $directory;
private static function init()
{
self::$directory = dirname(__FILE__) . DS . self::$options['folder'];
}
private static function getFilePath($key)
{
return self::$directory . DS . self::$options['prefix'] . $key;
}
public static function read($key)
{
self::init();
if (!file_exists(self::getFilePath($key))) {
return null;
}
$cached = unserialize(file_get_contents(self::getFilePath($key)));
if ($cached['expires'] <= strtotime('now')) {
unlink(self::getFilePath($key));
return null;
}
return $cached['content'];
}
public static function write($key, $object)
{
self::init();
$cached = array(
'expires' => strtotime(self::$options['expires']),
'content' => $object
);
$status = file_put_contents(self::getFilePath($key), serialize($cached));
return $status !== false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment