ホームページ  >  記事  >  バックエンド開発  >  php Cacheクラスインスタンスの詳しい説明

php Cacheクラスインスタンスの詳しい説明

小云云
小云云オリジナル
2018-03-10 11:03:3012169ブラウズ

この記事では主に php キャッシュ クラスの例の詳細な説明を共有し、キャッシュの使用方法をよりよく理解するのに役立つことを願っています。

推奨マニュアル: php完全自習マニュアル

1. インスタンス化

$cache = new Cache();

2. キャッシュ時間とキャッシュディレクトリを設定します

$cache = new Cache(60, '/any_other_path/');

最初のパラメータはキャッシュ秒数、2番目のパラメータはパラメータはキャッシュ パスであり、必要に応じて構成できます。
デフォルトでは、キャッシュ時間は 3600 秒で、キャッシュ ディレクトリは、cache/

3、読み取りキャッシュ

$value = $cache->get('data_key');

4、書き込みキャッシュ

$value = $cache->put('data_key', 'data_value');

完全な例:

$cache = new Cache();

//从缓存从读取键值 $key 的数据
$values = $cache->get($key);

//如果没有缓存数据
if ($values == false) {
	//insert code here...
	//写入键值 $key 的数据
	$cache->put($key, $values);
} else {
	//insert code here...
}
<?php
class Cache {
	private $cache_path;//path for the cache
	private $cache_expire;//seconds that the cache expires

	//cache constructor, optional expiring time and cache path
	public function Cache($exp_time=3600,$path="cache/"){
		$this->cache_expire=$exp_time;
		$this->cache_path=$path;
	}

	//returns the filename for the cache
	private function fileName($key){
		return $this->cache_path.md5($key);
	}

	//creates new cache files with the given data, $key== name of the cache, data the info/values to store
	public function put($key, $data){
		$values = serialize($data);
		$filename = $this->fileName($key);
		$file = fopen($filename, &#39;w&#39;);
	    if ($file){//able to create the file
	        fwrite($file, $values);
	        fclose($file);
	    }
	    else return false;
	}

	//returns cache for the given key
	public function get($key){
		$filename = $this->fileName($key);
		if (!file_exists($filename) || !is_readable($filename)){//can&#39;t read the cache
			return false;
		}
		if ( time() < (filemtime($filename) + $this->cache_expire) ) {//cache for the key not expired
			$file = fopen($filename, "r");// read data file
	        if ($file){//able to open the file
	            $data = fread($file, filesize($filename));
	            fclose($file);
	            return unserialize($data);//return the values
	        }
	        else return false;
		}
		else return false;//was expired you need to create new
 	}
}
?>
おすすめ関連記事:
1.TP5キャッシュの原理と使い方
2.phpデータキャッシュキャッシュクラス(ダウンロード)
関連動画おすすめ:
1.Dugu Jiiji (4)_PHPビデオチュートリアル

以上がphp Cacheクラスインスタンスの詳しい説明の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

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