Zend - The PHP Company




Miscellaneous

Add Code


Cacher - Easy and efficient variable cache system  

Type: class
Added by: liquidkernel
Entered: 14/09/2002
Last modified: 09/12/2001
Rating: - (fewer than 3 votes)
Views: 5067
Cacher allows you to cache variables (anything that can be put into a variable) for later use. This speeds up loading time, and reduces load on the data source.


<?

/**

class.cacher.php -- Class used to cache a variable in serialized form.

Written by Serge Stepanov (serge_AT_gfxcafe.com).
Feel free to email me with questions. If you find this useful, would be great to hear from you.

version 1.0 -

Changes:
- First release.

Notes:
- Get() method will only use
  the first occurrence, after which
  the loop will be broken.

Example:
    
include("class.cacher.php");

$cache = new Cacher;
// Get var if not 60 seconds old
$variable = $cache->Get("variable_with_id", 60); 

if (!$variable) {
    // Cache file expired or is inexistant
    // Do something to get new data
    $cache->Set("variable_with_id", $newdata);
    $variable = $newdata;
}

echo $variable;

**/

class Cacher {
    var 
$cacheDir "/tmp/";           // Where things are cached to (must have trailing slash!)
    
var $defaultCacheLife "3600"// How long to cache something for in seconds, default 1hr    
    
    /** 
        Set($varId, $varValue) --
        Creates a file named "cache.VARID.TIMESTAMP"
        and fills it with the serialized value from $varValue.
        If a cache file with the same varId exists, Delete()
        will remove it.
    **/
    
function Set($varId$varValue) {
        
$this->Delete($varId); // Clean up old caches with same varId
        
        
$fileHandler fopen($this->cacheDir "cache." $varId "." time(), "a"); // Create new file
        
fwrite($fileHandlerserialize($varValue));  // Write serialized data
        
fclose($fileHandler);
    }
    
    
/**
        Get($varID, $cacheLife) --
        Retrives the value inside a cache file
        specified by $varID if the expiration time
        (specified by $cacheLife) is not over.
        If expired, returns FALSE
    **/
    
function Get($varId$cacheLife="") {
        
$cacheLife = (!empty($cacheLife)) ? $cacheLife $this->defaultCacheLife// Set default cache life
        
        /* Loop through the directory looking for cache file */
        
$dirHandler dir($this->cacheDir);
        while (
$file $dirHandler->read()) {
            
/* Check for cache file with requested varId */
            
if (preg_match("/cache.$varId.[0-9]/"$file)) {
                
$cacheFileName explode("."$file); // Cache filename array
                
$cacheFileLife $cacheFileName[2]; // Cache file creation time
                
$cacheFile $this->cacheDir $file// Full location
                
                /* Check to see if cache file has expired or not */
                
if ((time() - $cacheFileLife) < $cacheLife) {
                    
$fileHandler fopen($cacheFile"r");
                    
$varValueResult fread($fileHandlerfilesize($cacheFile));
                    
fclose($fileHandler);
                    return 
unserialize($varValueResult); // Still good, return unseralized data
                
} else {
                    break; 
// Cache expired, break loop
                
}
            }
        }
        
$dirHandler->close();       
        return 
FALSE// Return false
    
}
    
    
/**
        Delete($varId) --
        Loops through the cache directory and
        removes any cache files with the varId
        specified in $varID
    **/    
    
function Delete($varId) {
        
$dirHandler dir($this->cacheDir);
        while (
$file $dirHandler->read()) {
            if (
preg_match("/cache.$varId.[0-9]/"$file)) {
                
unlink($this->cacheDir $file); // Delete cache file
            
}
        }
        
$dirHandler->close();
    }          
    
}

?>


Usage Example


include("class.cacher.php");

$cache = new Cacher;
$variable = $cache->Get("var1", 60); // 60 is the time out in seconds, default set inside source of object.

if (!$variable) {
    /**
    Cache file expired or doesn't exist.
    Do something to get new result.
    **/
    $cache->Set("var1", $newresult);
    $variable = $newresult;
}

echo $variable;


Rate This Script





Search



This Category All Categories