Skip to content

Instantly share code, notes, and snippets.

@johndyer
Created February 9, 2011 03:06
Show Gist options
  • Save johndyer/817809 to your computer and use it in GitHub Desktop.
Save johndyer/817809 to your computer and use it in GitHub Desktop.
Simple PHP Object Caching
<?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;
}
@krciga22
Copy link

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.

@XedinUnknown
Copy link

Race condition problem: between when has() reports, and actual access of the cache, the state may change.

@Krisseck
Copy link

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