With the development of micro-letter PHP, encountered Access_token long-term preservation of the problem, used to be in the framework of the cache directly set, get a bit is over. Now no frame available, had to write a cache for temporary use.
This cache class is used for caching some time-sensitive data, such as the access_token of the Micro-trust interface, the Access_token of Web page auth verification, etc.
The following code uses a local file to cache data.
Test $cache = new cache (); $cache->dir = ".
/cc/";
$cache->setcache ("Zhang", "Zhangsan", 100);
echo $cache->getcache ("Zhang");
$cache->removecache ("Zhang");
$cache->setcache ("Liu", "Liuqi", 100);
echo $cache->getcache ("Liu"); Class cache{Public $cacheFile = "Cache.json";//File Public $dir = "./cach2/";//directory/cache Public Function Setcache ($nam
E, $val, $expires _time) {$file = $this->hasfile ();
string-Array $str = file_get_contents ($file);
$arr = Json_decode ($str, true);
Value is empty, the cache if (empty ($val)) {unset ($arr [$name]) is removed;
}else{$arr [$name] = Array ("value" => $val, "Expires_time" => $expires _time, "Add_time" =>time ());
}//array-string $str = Json_encode ($arr);
File_put_contents ($file, $STR);
The Public Function GetCache ($name) {$file = $this->hasfile ();
string-Array $allArr = Json_decode ($str, true);
$arr = $ALLARR [$name]; if (! $arr | | | time () > ($arr ["expires_time"] + $arr ["Add_time"])) {$this->removecache ($name);//Expired Remove RetuRN false;
return $arr [' value '];
The Public Function RemoveCache ($name) {$this->setcache ($name, ', 0);
Private Function HasFile () {//If no cached file exists, create an if (!file_exists ($this->dir)) {mkdir ($this->dir);
if (!file_exists ($this->dir. $this->cachefile)) {Touch ($this->dir. $this->cachefile); Return $this->dir.
$this->cachefile; }
}
The above cache class has set, get, remove three kinds of operation. You can also customize the save path for the cached file, as long as you set the cache dir attribute.
The above is the PHP micro-trust in the development of data caching method, I hope to help you learn.