ホームページ  >  記事  >  バックエンド開発  >  PHPでキャッシュコードを実装する方法

PHPでキャッシュコードを実装する方法

王林
王林オリジナル
2021-10-21 17:05:311844ブラウズ

php キャッシュ クラス コードを実装するメソッド: [$cache = new Cache(); $values = $cache->get($key); if ($values == false) { $cache->put($key, $values)...]。

PHPでキャッシュコードを実装する方法

#この記事の動作環境: Windows10 システム、php 7、thinkpad t480 コンピューター。

使用説明:

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...
}

Cache.class.php

<?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
}
}
?>

推奨される学習:

php トレーニング

以上がPHPでキャッシュコードを実装する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

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