ホームページ  >  記事  >  バックエンド開発  >  phpファイルキャッシュクラスの定義と機能

phpファイルキャッシュクラスの定義と機能

墨辰丷
墨辰丷オリジナル
2018-06-11 14:32:331298ブラウズ

この記事では、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 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。