- <?php
- /**
- * @name cache
- * @deprecated control to cache data, $cache_out_time is a array to save cache date time out
- * @author caleng
- * @since 2008-08-05
- * @version 1.0
- */
- class cache
- {
- private $cache_dir; //缓存文件所放的相对网站目录的父目录
- private $expireTime = 180; //缓存的数据过期的时间,180秒
- function __construct($cache_dirname)
- {
- if (!is_dir($cache_dirname)) {
- if (!mkdir($cache_dirname,0777)) {
- $this->warn('Can not create the cache file.');
- return false;
- }
- }
- $this->cache_dir = $cache_dirname;
- }
- function __destruct()
- {
- echo 'Cache class bye.';
- }
- function get_url()
- {
- if (!isset($_SERVER['REQUEST_URI'])) {
- $url = $_SERVER['REQUEST_URI'];
- } else {
- $url = $_SERVER['SCRIPT_NAME'];
- $url .= (!emptyempty($_SERVER['QUERY_STRING']))?'?'.$_SERVER['QUERY_STRING']:'';
- }
- return $url;
- }
- function warn($errorstring)
- {
- echo "<B><font color='red'>Error:<pre>$errorstring</pre></font></B>";
- }
- function cache_page($pageurl,$pagedata)
- {
- if (!$fso=fopen($pageurl, 'w')) {
- $this->warn('Can not open the cache file.');
- return false;
- }
- //LOCK_EX:要取得独占锁定(写入的程序)
- if (!flock($fso,LOCK_EX)) {
- $this->warn('Can not lock the cache file.');
- return false;
- }
- if (!fwrite($fso, $pagedata)) {
- $this->warn('Can not write cache file.');
- return false;
- }
- //LOCK_UN:要释放锁定(无论共享或独占)
- flock($fso, LOCK_UN);
- fclose($fso);
- return true;
- }
- function display_cache($cacheFile)
- {
- if (!file_exists($cacheFile)) {
- $this->warn('Can not display the cache file.');
- return false;
- }
- $fso = fopen($cacheFile, 'r');
- $data = fread($fso, filesize($cacheFile));
- fclose($fso);
- return $data;
- }
- function readData($cacheFile = 'default_cache.txt')
- {
- $cacheFile = $this->cache_dir.'/'.$cacheFile;
- if (file_exists($cacheFile) && filemtime($cacheFile)>(time()-$this->expireTime)) {
- $data = $this->display_cache($cacheFile);
- } else {
- $data="from here wo can get it from mysql database,update time is <b>".date('l dS /of F Y h:i:s A')."</b>,过期时间是:".date('l dS /of F Y h:i:s A',time()+$this->expireTime)."----------";
- $this->cache_page($cacheFile,$data);
- }
- return $data;
- }
- }
- /*Test
- $test = new cache('D:/wwwroot/Test');
- $data = $test->readData();
- print_r($data);
- */
- ?>
PHP缓存类
最新推荐文章于 2010-10-25 16:15:00 发布