国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > PHP > 正文

一個簡單至極的PHP緩存類代碼

2024-05-04 23:39:46
字體:
來源:轉載
供稿:網友

這篇文章和大家分享了一個簡單至極的PHP緩存類代碼,緩存的應用對于php項目的開發來說尤為重要,需要的朋友可以參考下

網上關于 PHP 緩存類的資料很多,不過這個類應該是我見過功能滿足需求,但又無比簡潔的一個。廢話不多說,直接看代碼吧!

使用說明: 1、實例化

$cache = new Cache();

2、設置緩存時間和緩存目錄

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

第一個參數是緩存秒數,第二個參數是緩存路徑,根據需要配置。

默認情況下,緩存時間是 3600 秒,緩存目錄是 cache/

3、讀取緩存

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

4、寫入緩存

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

完整實例:

 

 
  1. $cache = new Cache();  
  2.  
  3. //從緩存從讀取鍵值 $key 的數據  
  4. $values = $cache->get($key);  
  5.  
  6. //如果沒有緩存數據  
  7. if ($values == false) {  
  8. //insert code here...  
  9. //寫入鍵值 $key 的數據  
  10. $cache->put($key, $values);  
  11. else {  
  12. //insert code here...  
  13. }  

Cache.class.php

 

 
  1. <?php  
  2. class Cache {  
  3. private $cache_path;//path for the cache  
  4. private $cache_expire;//seconds that the cache expires  
  5.  
  6. //cache constructor, optional expiring time and cache path  
  7. public function Cache($exp_time=3600,$path="cache/"){  
  8. $this->cache_expire=$exp_time;  
  9. $this->cache_path=$path;  
  10. }  
  11.  
  12. //returns the filename for the cache  
  13. private function fileName($key){  
  14. return $this->cache_path.md5($key);  
  15. }  
  16.  
  17. //creates new cache files with the given data, $key== name of the cache, data the info/values to store  
  18. public function put($key, $data){  
  19. $values = serialize($data);  
  20. $filename = $this->fileName($key);  
  21. $file = fopen($filename, 'w');  
  22. if ($file){//able to create the file  
  23. fwrite($file, $values);  
  24. fclose($file);  
  25. }  
  26. else return false;  
  27. }  
  28.  
  29. //returns cache for the given key  
  30. public function get($key){  
  31. $filename = $this->fileName($key);  
  32. if (!file_exists($filename) || !is_readable($filename)){//can't read the cache  
  33. return false;  
  34. }  
  35. if ( time() < (filemtime($filename) + $this->cache_expire) ) {//cache for the key not expired  
  36. $file = fopen($filename, "r");// read data file  
  37. if ($file){//able to open the file  
  38. $data = fread($file, filesize($filename));  
  39. fclose($file);  
  40. return unserialize($data);//return the values  
  41. }  
  42. else return false;  
  43. }  
  44. else return false;//was expired you need to create new  
  45. }  
  46. }  
  47. ?> 

相信大家一定會喜歡這個簡潔的php緩存類代碼,希望對大家的學習有所幫助。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 麻城市| 庄浪县| 齐齐哈尔市| 岑溪市| 麦盖提县| 兴仁县| 大方县| 正宁县| 临朐县| 额济纳旗| 平远县| 乌海市| 九龙坡区| 岫岩| 牙克石市| 兴国县| 安阳市| 武强县| 泸州市| 涿州市| 马鞍山市| 梧州市| 五常市| 塔河县| 黔南| 望谟县| 收藏| 西峡县| 西乌珠穆沁旗| 大同县| 建平县| 新沂市| 沅江市| 河北省| 潮州市| 岑巩县| 新田县| 敖汉旗| 白山市| 南郑县| 铜陵市|