PHPコード編(八)--phpはファイルキャッシュの読み書きを実現する
10068 ワード
最近引き継いだフォーラムプロジェクトは、コードについては特に熟知していないため、キャッシュが必要な場所があるため、fileベースのものを書いたという.put_contents関数ファイルの書き込みとfopen関数ファイルの開き、実装されたファイルキャッシュは、具体的には使用できますが、高同時性の場合、マルチユーザーが同時にアクセスすると、どうなるか分かりません.
このブログを見たら、意見やコメントをしてほしいです.主にphpwindというフォーラムのキャッシュは確かによく知られていませんが、自分で書いたキャッシュは、実はファイルの読み書きです.本当にキャッシュしています.
次はコード本文です.
呼び出すと、直接
このブログを見たら、意見やコメントをしてほしいです.主にphpwindというフォーラムのキャッシュは確かによく知られていませんが、自分で書いたキャッシュは、実はファイルの読み書きです.本当にキャッシュしています.
次はコード本文です.
php
/**
*
* User:WuYan
* Time:2020.5.12
*/
class cache
{
const CACHE_PATH = './data/file/';//
const CACHE_TYPE = '.md';//
//
static private $instance;
// new
private function __construct(){}
// clone
private function __clone(){}
static public function getInstance()
{
// $instance Singleton ,
if (!self::$instance instanceof self) {
self::$instance = new self();
}
return self::$instance;
}
/**
*
* @param [type] $key string
* @param [type] $value array
* @param integer $time s
* @return [booleans]
*/
public static function setCache($key, $value, $time = 0)
{
if (!is_array($value)) {
return false;
}
//
if (!file_exists(self::CACHE_PATH)) {
$mode = intval('0777', 8);
mkdir(self::CACHE_PATH, $mode, true);
}
$data = [
'time' => $time ? time() + $time : 0,
'data' => $value,
];
// ,
$result = file_put_contents(self::CACHE_PATH.'/'.$key.self::CACHE_TYPE, json_encode($data));
if ($result) {
return true;
} else {
return false;
}
}
/**
*
* @param [type] $key string
* @return [array]
*/
public static function getCache($key)
{ //
$file_path = self::CACHE_PATH.$key.self::CACHE_TYPE;
if (file_exists($file_path)) {
//
$fp = fopen($file_path,"r");
// ,
$string = fread($fp,filesize($file_path));
if (!$string) {
return false;
}
$array = json_decode($string, true);
if (empty($array['data'])) {
return false;
}
//
if ($array['time']) {
if ($array['time'] > time()) {//
$result_data = $array['data'];
} else {
//
fclose($fp);
unlink($file_path);
return false;
}
} else {//
$result_data = $array['data'];
}
//
fclose($fp);
return $result_data;
} else {
return false;
}
}
}
呼び出すと、直接
cache::setCache('pw_area',['100'=>' ','101'=>' '],3600);