首页 >后端开发 >php教程 >php中使用文件缓存的例子

php中使用文件缓存的例子

WBOY
WBOY原创
2016-07-25 08:45:221282浏览

在web开发中,可以通过文件缓存,大大缓解数据库的压力。 如下代码是php中使用文件缓存的例子。

CacheLayer.php

  1. class CacheLayer{
  2. protected $root = "";
  3. protected $cache = "";
  4. protected $key = "";
  5. protected $life = 0;
  6. public function __construct($key, $root = "/cachelayer"){
  7. $this->root = $_SERVER["DOCUMENT_ROOT"].$root;
  8. $this->key = $key;
  9. }
  10. public function expired($life_span){
  11. $this->life = $life_span;
  12. $file = $this->root."/".$this->key.".cachelayer";
  13. if(is_file($file)){
  14. $mtime = filemtime($file);
  15. return (time() >= ($mtime + $this->life));
  16. }else{
  17. return true;
  18. }
  19. }
  20. public function put($content){
  21. $file = $this->root."/".$this->key.".cachelayer";
  22. if(!is_dir(dirname($this->root))){
  23. return false;
  24. }
  25. $this->delete();
  26. $content = json_encode($content);
  27. return (bool)file_put_contents($file, $content);
  28. }
  29. public function get(){
  30. $file = $this->root."/".$this->key.".cachelayer";
  31. if(is_file($file)){
  32. return json_decode(file_get_contents($file), true);
  33. }
  34. return array();
  35. }
  36. public function delete(){
  37. $file = $this->root."/".$this->key.".cachelayer";
  38. if(is_file($file)){
  39. unlink($file);
  40. return true;
  41. }
  42. return false;
  43. }
  44. }
复制代码

example.php

  1. // Load the cachelayer and the database connection (db connection is optional)
  2. require_once "CacheLayer.php";
  3. require_once "db_connection.php";
  4. // Create a instance of the cachelayer
  5. $cl_nav = new CacheLayer("navigation");
  6. // Check to see if the cache is expired (60 * 10 = 10 minutes)
  7. if($cl_nav->expired(60 * 10)){
  8. echo "Cache doesn't exist or is expired. Rebuilding...
    ";
  9. // if the cache is expired rebuild it
  10. $result = mysql_query("select id, title from navigation");
  11. $new_cache = array();
  12. while($row = mysql_fetch_assoc($result)){
  13. $new_cache[] = $row;
  14. }
  15. // Save the array into the cache
  16. $cl_nav->put($new_cache);
  17. }
  18. echo "Loading from cache...
    ";
  19. // Get the cache
  20. $cache = $cl_nav->get();
  21. // Display the cache
  22. foreach($cache as $row){
  23. $id = $row["id"];
  24. $title = $row["title"];
  25. echo "$title
    ";
  26. }
复制代码

php


声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn