<?php
define
('CACHE_DIRECTORY''/var/tmp/');
define('CACHE_PREFIX''zeegismyhero_');

/*
$c = new cache();
if (!$data = $c->get('group', 'unique id'))
{
    $data = 'this was cached at '.date();

    $c->set('group', 'unique id', 10, $data);
}
echo $data;
*/
class cache
{
    
/**
    * Stores data
    * 
    * @param string $group Group to store data under
    * @param string $id    Unique ID of this data
    * @param int    $ttl   How long to cache for (in minutes)
    */
    
function write($group$id$ttl$data)
    {
        
$filename $this->get_filename($group$id);

        if (
$fp fopen($filename'xb'))
        {

            if (
flock($fpLOCK_EX))
                
fwrite($fp$data);
            
fclose($fp);

            
// Set filemtime
            
touch($filenametime() + $ttl*60);
        }
    }
        
    
/**
    * Reads data
    * 
    * @param string $group Group to store data under
    * @param string $id    Unique ID of this data
    */
    
function read($group$id)
    {
        
$filename $this->get_filename($group$id);

        return 
file_get_contents($filename);
    }
        
    
/**
    * Determines if an entry is cached
    * 
    * @param string $group Group to store data under
    * @param string $id    Unique ID of this data
    */
    
function is_cached($group$id)
    {
        
$filename $this->get_filename($group$id);

        if (
$this->enabled && file_exists($filename) && filemtime($filename) > time())
            return 
true;
            
        @
unlink($filename);

        return 
false;
    }
        
    
/**
    * Builds a filename/path from group, id and
    * store.
    * 
    * @param string $group Group to store data under
    * @param string $id    Unique ID of this data
    */
    
function get_filename($group$id)
    {
        
$id md5($id);

        return 
CACHE_DIRECTORY CACHE_PREFIX "{$group}_{$id}";
    }

    
/**
    * Retrieves data from the cache
    * 
    * @param  string $group Group this data belongs to
    * @param  string $id    Unique ID of the data
    * @return mixed         Either the resulting data, or null
    */
    
function get($group$id)
    {
        if (
$this->is_cached($group$id))
            return 
unserialize($this->read($group$id));
            
        return 
null;
    }

    
/**
    * Stores data in the cache
    * 
    * @param string $group Group this data belongs to
    * @param string $id    Unique ID of the data
    * @param int    $ttl   How long to cache for (in seconds)
    * @param mixed  $data  The data to store
    */
    
function set($group$id$ttl$data)
    {
        
$this->write($group$id$ttlserialize($data));
    }
}
?>