Login   Register  
PHP Classes
elePHPant
Icontem

File: class.cache.php

Recommend this page to a friend!
Stumble It! Stumble It! Bookmark in del.icio.us Bookmark in del.icio.us
  Classes of dietrich ayala  >  Caching class  >  class.cache.php  >  Download  
File: class.cache.php
Role: ???
Content type: text/plain
Description: content caching class
Class: Caching class
Author: By
Last change:
Date: 2000-11-06 18:28
Size: 2,183 bytes
 

Contents

Class file image Download
<?
/*
questions, contact me:
dietrich ayala
dietricha@subpop.com

todo:
* add expiration functionality - a time/date var that indicates a maximum age for a cache_file
* actually benchmark the class. see how much it decreases script execution time

my *basic* performance test:
	(benchmarked with Dirks Webstress - http://www.paessler.com)
	server: pentiumII 400 256mb RAM
	webserver: apache 1.3.12
	php: version 4.02 w/ Zend Optimizer
	mysql: version 3.21.33b
	
	script: hit mysql once for 700 rows of 12 fields each
	and formatted results into nested tables, one per row.
	
	
	avg request time w/o caching:
	880 milleseconds
	avg request time w/ caching:
	594 milleseconds

usage:

$cache = new cache;
$args = array_merge($HTTP_POST_VARS,$HTTP_GET_VARS);
$args[] = $PHP_SELF;
$buffer = $cache->check_cache($args);

if(!$buffer){
	// normal script execution here
	// but instead of printing, load all
	// output into a buffer var ($buffer).

	// load buffer var into cache file
	if(!$cache->set_cache($buffer)){
		print "couldn't create cache file";
	}
}
print $buffer;

*/

class cache {

	function cache(){
		$this->cache_name = "";
		$this->debug_flag = true;
		$this->cache_dir = "/home/www/scripts/cache";
	}
	
	function check_cache($args){
		if($args["PHPSESSID"]){
			$this->debug("found a session id");
			unset($args["PHPSESSID"]);
		}
		
		$this->cache_name = strtolower(ereg_replace("[\"\'\-\;\:\,\\\/]","_",str_replace(" ","",join("_",$args)))).".cache";
		$this->debug("cache_name: $this->cache_name");
		clearstatcache();
		if(file_exists("$this->cache_dir/$this->cache_name")){
			$this->debug("and cache file exists!");
			return join("",file("$this->cache_dir/$this->cache_name"));
		}
		return false;
	}
	
	function set_cache($buffer){
		// write buffer to cache file
		if($fp = @fopen("$this->cache_dir/$this->cache_name","w")){
			fputs($fp,$buffer);
			fclose($fp);
			if(!$cache = fopen("$this->cache_dir/$this->cache_name","r")){
				return false;
			}
		}
		return true;
	}
	
	function debug($string){
		if($this->debug_flag == true){
			print "$string<br>";
		}
	}
}
?>