If the number of visits is large, it will put a lot of burden on the database, so it is very necessary to do a good PHP data cache for content that changes infrequently. I made a simple PHP "file cache" class. I hope Helpful to everyone.
The idea is as follows:
For general variables, change the variable into the format of php language and write it to the file. It only takes a long time to include this file. Because the cache is loaded;
For array-type variables, convert the array into a string that defines the array in PHP language, and write it to the file. It only takes the time to include it, which is equivalent to loading the cache;
Cache cache time For control, compare the creation time of the cache file with the current time. If the update time is not reached, the cache is read directly. If the update time is reached, the database is queried, the data is returned, and the cache is updated. (Not yet implemented)
The following is my php-kcache class (php_kcache_class.php):
Note: If it is a cache string, please add one more escape character' ', that is, "n" should be written as "\n".
/*
//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 is bug-free, and is not responsible for any problems caused by using this program
//.
*/
class php_kcache {
//Relative or absolute directory, do not add '/' at the end
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) . ';';
$cache = $pre . $str . $end;
$cache_file = $this->cache_dir . '/' . $name . $this->cache_extension;
if($fp = @fopen($cache_file, 'wb')) {
echo $ cache_file;
, from discuz!
function arrayeval($array, $level = 0) {
if(!is_array($array)) {
return "'".$array."'";
🎜>} $ Evaluate = "Arrayn $ Space (n";
$ Commma = $ Space;
If (IS_ARRAY ($ Array)) {
Foreach ($ array as $ key = & gt ; $val) {
$key = is_string($key) ? '''.addcslashes($key, ''\').''' : $key;
$val = !is_array($val ) && (!preg_match("/^-?[1-9]d*$/", $val) || strlen($val) > 12) ? '''.addcslashes($val, ''\' ).'' : $val;
🎜> } else { ,n$space";
🎜> $evaluate .= "n$space)";
return $evaluate;
The simplest calling method:
Copy the code The code is as follows:
include '. /php_kcache_class.php';
$pc = new php_kcache;
$a = array('a', 'b', 'c');
$pc->set_cache('a', addslashes($a));
Complex calling method (with cache time control) - will be added later… to be continued…
http://www.bkjia.com/PHPjc/321536.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/321536.htmlTechArticleIf the number of visits is large, it will cause a great burden on the database, so content that changes infrequently should be done well PHP data cache (caching) is very necessary. I made a simple PHP "text...