PHP程序缓存之文件缓存处理方式
在开发程序过程中,缓存的设置大大提升程序效率,减小数据库负载。
基本配置缓存和常规配置缓存
基本配置缓存在项目开发中类似这样子的格式:
文件:config.php
$CFG[‘database‘] = ‘mysql‘; $CFG[‘pconnect‘] = ‘0‘; $CFG[‘db_host‘] = ‘localhost‘; $CFG[‘db_name‘] = ‘appcom‘; $CFG[‘db_user‘] = ‘root‘; $CFG[‘db_pass‘] = ‘123456‘; $CFG[‘db_charset‘] = ‘utf8‘;
常规配置缓存类似这样的:例如文件x.php
return array ( ‘a‘=>‘‘,‘b‘=>‘‘,‘c‘=>‘‘,‘d‘=>‘‘, ‘aa‘=>array(‘x‘=>‘‘,‘y‘=>,‘z‘=>‘‘), ‘bb‘=>array(‘x‘=>‘‘,‘y‘=>,‘z‘=>‘‘), ‘cc‘=>array(‘x‘=>‘‘,‘y‘=>,‘z‘=>‘‘));
缓存配置程序代码:
基本配置的更新:
$tmp = file_get(‘config.inc.php‘); foreach($setting as $k=>$v) { $tmp = preg_replace("/[$]CFG\[‘$k‘\]\s*\=\s*[\"‘].*?[\"‘]/is", "\$CFG[‘$k‘] = ‘$v‘", $tmp);
常规配置的更新:例如文件名为y.php
cache_write(‘y.php‘, $setting); function cache_write($file, $string, $dir = ‘‘) { if(is_array($string)) $string = "<?php defined(‘IN_KELE‘) or exit(‘Access Denied‘); return ".strip_nr(var_export($string, true))."; ?>"; $file = $file; $strlen = file_put($file, $string); return $strlen; } function strip_nr($string, $js = false) { $string = str_replace(array(chr(13), chr(10), "\n", "\r", "\t", ‘ ‘),array(‘‘, ‘‘, ‘‘, ‘‘, ‘‘, ‘‘), $string); if($js) $string = str_replace("‘", "\‘", $string); return $string; } function file_put($filename, $data) { $phpServer=strpos(strtoupper(PHP_OS), ‘WIN‘) !== false ? true: false; dir_create(dirname($filename)); if(@$fp = fopen($filename, ‘wb‘)) { flock($fp, LOCK_EX); $len = fwrite($fp, $data); flock($fp, LOCK_UN); fclose($fp); if($phpServer) @chmod($filename, $phpServer); return $len; } else { return false; } } function file_get($filename) { return @file_get_contents($filename); }