Last active
August 29, 2015 14:05
-
-
Save lucasgameiro/bf7ede00a97bd9efb643 to your computer and use it in GitHub Desktop.
Simple file cache static class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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