php檔案快取類別的定義及功能

墨辰丷
發布: 2023-03-31 15:04:02
原創
1307 人瀏覽過

這篇文章主要介紹了php檔案快取類別用法,以實例形式較為詳細的分析了php檔案快取類別的定義、功能及具體使用技巧,非常具有實用價值,需要的朋友可以參考下

本文實例講述了php檔案快取類別用法。具體如下:

<?php
/**
 * 简单的文件缓存类
 *
 */
class XZCache{
 // default cache time one hour
 var $cache_time = 3600;
 // default cache dir
 var $cache_dir = &#39;./cache&#39;;
 public function __construct($cache_dir=null, $cache_time=null){
  $this->cache_dir = isset($cache_dir) ? $cache_dir : $this->cache_dir;
  $this->cache_time = isset($cache_time) ? $cache_time : $this->cache_time;
 }
 public function saveCache ($key, $value){
  if (is_dir($this->cache_dir)){
   $cache_file = $this->cache_dir . &#39;/xzcache_&#39; . md5($key);
   $timedif = @(time() - filemtime($cache_file));
   if ($timedif >= $this->cache_time) {
    // cached file is too old, create new
    $serialized = serialize($value);
    if ($f = @fopen($cache_file, &#39;w&#39;)) {
     fwrite ($f, $serialized, strlen($serialized));
     fclose($f);
    }
   }
   $result = 1;
  }else{
   echo "Error:dir is not exist.";
   $result = 0;
  }
  return $result;
 }
 /**
  * @return array 
  *   0 no cache
  *    1 cached
  *    2 overdue
  */
 public function getCache ($key) {
  $cache_file = $this->cache_dir . &#39;/xzcache_&#39; . md5($key);
  if (is_dir($this->cache_dir) && is_file($cache_file)) {
   $timedif = @(time() - filemtime($cache_file));
   if ($timedif >= $this->cache_time) {
    $result[&#39;cached&#39;] = 2;
   }else{
    // cached file is fresh enough, return cached array
    $result[&#39;value&#39;] = unserialize(file_get_contents($cache_file));
    $result[&#39;cached&#39;] = 1;
   }
  }else {
   echo "Error:no cache";
   $result[&#39;cached&#39;] = 0;
  }
  return $result;
 }
} //end of class
登入後複製

用法範例如下:

$cache = new XZCache();
$key = &#39;global&#39;;
$value = $GLOBALS;
$cache->saveCache($key, $value);
$result = $cache->getCache($key);
var_dump($result);
登入後複製

總結:以上就是這篇文章的全部內容,希望能對大家的學習有所幫助。

相關推薦:

簡述PHP中提供的魔術方法

php大規模資料提交的方法

PHP中foreach()的使用方法

以上是php檔案快取類別的定義及功能的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
php
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!