Version: 1.0
Type: Class
Category: Databases
License: GNU General Public License
Description: Caching system, fast and flexible
<?
/*
2001-03-01 - Fredrik (fln@mendosus.org)
Cachinging....
M4Cache version 1.0
Usage:
include "class.M4Cache.php";
$cache = new M4Cache(true, true);
$page = "<html>....</html>";
$cache->process($page);
exit;
*/
class M4Cache
{
var $cacheDir = "/home/foo/cache"; //no trailing slash(/)
var $filename = "";
var $pid = 0;
var $compress = false;
var $cache;
/*
Paremeters
1st = compress the cache file
2nd = cache on/off
3rs = manualy fake the filename (ie: backstage pass)
*/
function M4Cache($compress_ = false, $cache_ = true, $fakenr = false)
{
$this->cache = $cache_;
if ($this->cache == false) //no caching
{
return false;
}
$start = $this->utime();
$this->compress = $compress_;
$this->pid = "." . getmypid();
$ptr = getenv ("QUERY_STRING");
$ptr = strtr($ptr, "/", "_");
$this->filename = $this->cacheDir . getenv("SCRIPT_NAME") . "?" . $ptr;
if ($fakenr != false)
{
$this->filename .= "&fakeNR=$fakenr";
}
if (file_exists($this->filename) == true)
{
$fp = fopen($this->filename, "r");
$size = filesize($this->filename);
$ptr = fread($fp, $size);
fclose($fp);
$end = $this->utime();
$runtime = $end - $start;
echo $ptr . "\n<!-- CACHE Completed in $runtime seconds -->";
exit;
}
return false;
}
function process($ptr, $start = null)
{
if ($this->cache == false) //no caching
{
echo $ptr;
return false;
}
if ($start == null)
{
$start = $this->utime();
}
$fp = @fopen($this->filename . $this->pid, "w");
if ($fp == false)
{
echo "<pre>Error[M4.Cache]: unable to open cache</pre>";
exit;
}
if ($this->compress == true)
{
$ptr = @eregi_replace("[[:space:]]+", " ", $ptr);
if ($ptr == "")
{
echo "<pre>Error[M4.Cache]: timeout</pre>";
exit;
}
$ptr = ereg_replace("[\n\t]", "", $ptr );
// $ptr = ereg_replace("[\ \ ]*", " ", $ptr );
}
fwrite($fp, $ptr);
fclose($fp);
@unlink($this->filename);
rename($this->filename . $this->pid, $this->filename);
$end = $this->utime();
$runtime = $end - $start;
echo $ptr . "\n<!-- DB Completed in $runtime seconds -->";
return true;
}
function getFilename()
{
echo $this->filename;
}
function utime ()
{
$time = explode( " ", microtime());
$usec = (double)$time[0];
$sec = (double)$time[1];
return $sec + $usec;
}
}?>