Created
February 9, 2011 03:06
-
-
Save johndyer/817809 to your computer and use it in GitHub Desktop.
Simple PHP Object Caching
This file contains hidden or 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 | |
// Super simple caching class | |
class PhpCache { | |
protected $path = null; | |
protected $duration = null; | |
function __construct ( $path, $duration = 60) { | |
$this->path = $path; | |
$this->duration = $duration; | |
} | |
function get( $id ) { | |
$file = $this->path . $id . '.cache'; | |
if (file_exists($file) && time() - filemtime($file) < $this->duration) { | |
return unserialize( file_get_contents($file) ); | |
} else { | |
return null; | |
} | |
} | |
function set( $id, $obj) { | |
$file = $this->path . $id . '.cache'; | |
file_put_contents($file, serialize($obj)); | |
} | |
} | |
?> | |
<? | |
// Usage | |
$cache = new PhpCache(dirname(__FILE__).'\\cache\\', 600); | |
$key = 'mykey'; | |
$value = $cache->get($key); | |
if ($value == null) { | |
$value = 'new value'; | |
$cache->set($key, $value); | |
echo 'created ' . $value; | |
} else { | |
echo 'got ' . $value; | |
} |
Race condition problem: between when has()
reports, and actual access of the cache, the state may change.
If you are on Linux, change \\cache\\
to /cache/
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Awesomely simple little script :)
Quick and easy to implement, and even easier to modify to add a few more features like cache filename prefixes, and durations for specific cache ID's.