ホームページ  >  記事  >  バックエンド開発  >  PHP はデータ キャッシュ プログラムを実装します_PHP チュートリアル

PHP はデータ キャッシュ プログラムを実装します_PHP チュートリアル

WBOY
WBOYオリジナル
2016-07-13 17:07:20778ブラウズ

/**
 * キャッシュクラス
 */

クラスキャッシュ{
 /**
  * キャッシュパス
  *
  * @var 文字列
 */
 var $cache_path;
 /**
  *タイムアウト
  *
  * @var 整数
 */
 var $time = 60;
 
 /**
  * このクラスの構築
  *
  * @param string $cache_path
  * @return キャッシュ
 */
 関数キャッシュ($cache_path = 'キャッシュ') {
  if(is_dir($cache_path)) {
   $this->cache_path = rtrim($cache_path,'/').'/';
  } その他 {
   die('キャッシュディレクトリが存在しません。');
  }
 }
 
 /**
  * タイムアウトを設定します
  *
  * @param integer $time
  * @return boolean
 */
 関数 setTime($time) {
  if(isset($time) && is_integer($time)) {
   $this->time = $time;
   true を返します;
  } その他 {
   false を返します;
  }
 }
 
 /**
  * 読み取りキャッシュ
  *
  * @param string $cache_id
  * @return 混合
 */
 関数 read($cache_id) {
  $cache_file = $this->cache_path.$cache_id.'.cache';
  if(!file_exists($cache_file)) {
   false を返します;
  }
  $mtime = filemtime($cache_file);
  if((time() - $mtime) > $this->time) {
   false を返します;
  } その他 {
   $fp = fopen($cache_file,'r');
   $content = fread($fp,filesize($cache_file));
   fclose($fp);
   設定を解除($fp);
   if($content) {
    return unserialize($content);
   } その他 {
    false を返します;
   }
  }
 }
 
 /**
  * ファイルにキャッシュを書き込む
  *
  * @param string $content
  * @param string $cache_id
  * @return boolean
 */
 関数 write($content,$cache_id) {
  $cache_file = $this->cache_path.$cache_id.'.cache';
  if(file_exists($cache_file)) {
   @unlink($cache_file);
  }
  $fp = fopen($cache_file,'w');
  $content = シリアライズ($content);
  if(fwrite($fp,$content)) {
   fclose($fp);
   設定を解除($fp);
   true を返します;
  } その他 {
   fclose($fp);
   設定を解除($fp);
   false を返します;
  }
 }
 
 /**
  * すべてのキャッシュを削除します
  *
  * @param string $path
  * @return boolean
 */
 関数 cleanCache($path = 'キャッシュ') {
  if(is_dir($path)) {
   $path = rtrim($path,'/').'/';
   $handler = opendir($path);
   while (($f = readdir($handler)) !== false) {
    if(!is_dir($f)) {
     if($f != '.' && $f != '..') {
      @unlink($path.$f);
     }
    } その他 {
     $this->cleanCache($f);
    }
   }
  } その他 {
   false を返します;
  }
 }
}

?>

www.bkjia.comtru​​ehttp://www.bkjia.com/PHPjc/630437.html技術記事 ?php /*** キャッシュクラス*/ class Cache { /*** キャッシュパス * * @var 文字列*/ var $cache_path; /*** タイムアウト * * @var integer*/ var $time = 60; /** * このクラスの構成体 * * @p...
声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。