温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

PHP怎么实现数据缓存类

发布时间:2021-11-02 10:15:47 来源:亿速云 阅读:120 作者:小新 栏目:编程语言

这篇文章主要介绍了PHP怎么实现数据缓存类,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。

思路是这样的:

对于一般的变量,把该变量变成PHP语言的格式,写到文件中,用时只要include这个文件就相当于加载了PHP数据缓存类了;

对于array型的变量,把array转化为PHP语言定义array的字符串,写到文件中,用时也只要include就相当于加载了cache了;

PHP数据缓存类时间上的控制,通过获取缓存文件的创建时间和现在的时间进行对比,如果没有到更新时间,直接读取缓存,如果到了更新时间,查询数据库,返回数据,再更新缓存。(尚未实现)

下面是我的PHP-kcache类(PHP_kcache_class.PHP):

注:如果是缓存字符串,请把转义字符多写一个’\',即”\n”要写成”\\n”。

  1. /*  

  2. //PHP-kcache class v_0.1  

  3. //Author: kangzj  

  4. //Email : kangzj@mail.bnu.edu.cn  

  5. //Blog : http://kangzj.net.ru  

  6. //作者不保证本程序没有bug,对于使用本程序  

  7. //而引起的任何问题不担负任何责任。  

  8. */  

  9. class PHP_kcache {  

  10. //相对或者绝对目录,末尾不要加 '/'  

  11. var $cache_dir = './cache';  

  12. var $cache_extension = '.cache.PHP';  

  13. function set_cache($name, $value){  

  14. $pre = "< ?\n//Cache Created at: "
    .date('Y-m-d H:i:s')."\n";  

  15. if(!is_array($value)){  

  16. $value = $value;  

  17. $str = "\$$name = '$value';";  

  18. }else{  

  19. $str = "\$$name = " . $this->
    arrayeval($value) . ';';  

  20. }  

  21. $end = "\n?>";  

  22. echo $cache = $pre . $str . $end;  

  23. $cache_file = $this->cache_dir . 
    '/' . $name . $this->cache_extension;  

  24. if($fp = @fopen($cache_file, 'wb')) {  

  25. fwrite($fp, $cache);  

  26. fclose($fp);  

  27. return true;  

  28. } else {  

  29. echo $cache_file;  

  30. exit('Can not write to cache files, 
    please check cache directory ');  

  31. return false;  

  32. }  

  33. }  

  34. //将array变成字符串, 来自discuz!  

  35. function arrayeval($array, $level = 0) {  

  36. if(!is_array($array)) {  

  37. return "'".$array."'";  

  38. }  

  39. $space = '';  

  40. for($i = 0; $i < = $level; $i++) {  

  41. $space ."\t";  

  42. }  

  43. $evaluate = "Array\n$space(\n";  

  44. $comma = $space;  

  45. if(is_array($array)) {  

  46. foreach($array as $key => $val) {  

  47. $key = is_string($key) ? '\''.addcslashes
    ($key, '\'\\').'\'' : $key;  

  48. $val = !is_array($val) &&
     (!preg_match("/^\-?[1-9]\d*$/", $val)
     || strlen($val) > 12) ? '\''.addcslashes
    ($val, '\'\\').'\'' : $val;  

  49. if(is_array($val)) {  

  50. $evaluate ."$comma$key => ".
    arrayeval($val, $level + 1);  

  51. } else {  

  52. $evaluate ."$comma$key => $val";  

  53. }  

  54. $comma = ",\n$space";  

  55. }  

  56. }  

  57. $evaluate ."\n$space)";  

  58. return $evaluate;  

  59. }  


最简单的PHP数据缓存类调用方法:

include './PHP_kcache_class.PHP';  $pc = new PHP_kcache;  $a = array('a', 'b', 'c');  $pc->set_cache('a', addslashes($a));

感谢你能够认真阅读完这篇文章,希望小编分享的“PHP怎么实现数据缓存类”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

php
AI