If a large number of visits to the database will cause a lot of burden, so for the change does not often content to do well PHP data cache (cache) is very necessary, I made a simple php "file caching" class, I hope to help.
The idea is this:
For a general variable, the variable into a PHP language format, written to the file, as long as the include this file is equivalent to loading the cache;
For array-type variables, the array is converted to the PHP language definition array string, written to the file, as long as the include is equivalent to loading the cache;
Cached cache time control, by getting the cache file creation time and current time to compare, if not to update the time, direct read cache, if the update time, query the database, return data, and then update the cache. (not yet implemented)
Here's my Php-kcache class (php_kcache_class.php):
Note: If it is a cached string, write the escape character one more ' \ ', that is, ' \ n ' to be written as ' \\n '.
Copy Code code as follows:
/*
Php-kcache class v_0.1
Author:kangzj
email:kangzj@mail.bnu.edu.cn
blog:http://kangzj.net.ru
The author does not guarantee that this program does not have bugs, for the use of this program
and any problems arising from it are not liable.
*/
Class Php_kcache {
Relative or absolute directory, end don't add '/'
var $cache _dir = './cache ';
var $cache _extension = '. cache.php ';
function Set_cache ($name, $value) {
$pre = "< \n//cache Created at:". Date (' y-m-d h:i:s '). " \ n ";
if (!is_array ($value)) {
$value = $value;
$str = "\$ $name = ' $value ';";
}else{
$str = "\$ $name =". $this->arrayeval ($value). ';';
}
$end = "\n?>";
echo $cache = $pre. $str. $end;
$cache _file = $this->cache_dir. '/' . $name. $this->cache_extension;
if ($fp = @fopen ($cache _file, ' WB ')) {
Fwrite ($fp, $cache);
Fclose ($FP);
return true;
} else {
echo $cache _file;
Exit (' Can not write to cache files, please check cache directory ');
return false;
}
}
Turn array into a string from the discuz!
function Arrayeval ($array, $level = 0) {
if (!is_array ($array)) {
Return "'" $array. "'";
}
$space = ';
for ($i = 0; $i < = $level; $i + +) {
$space. = "T";
}
$evaluate = "Array\n$space (\ n";
$comma = $space;
if (Is_array ($array)) {
foreach ($array as $key => $val) {
$key = is_string ($key)? '/'. Addcslashes ($key, ' \ \ \ \]. \ ': $key;
$val =!is_array ($val) && (!preg_match ("/^\-?[ 1-9]\d*$/", $val) | | strlen ($val) > 12)? '/'. Addcslashes ($val, ' \ \ \ \]. \ ': $val;
if (Is_array ($val)) {
$evaluate. = "$comma $key =>". Arrayeval ($val, $level + 1);
} else {
$evaluate. = "$comma $key => $val";
}
$comma = ", \n$space";
}
}
$evaluate. = "\n$space)";
return $evaluate;
}
}
simplest method of invocation:
Copy Code code as follows:
Include './php_kcache_class.php ';
$pc = new Php_kcache;
$a = Array (' A ', ' B ', ' C ');
$pc->set_cache (' A ', addslashes ($a));
Complex invocation method (plus cache time control)----------------continued