Home  >  Article  >  Backend Development  >  Example of using file cache in php

Example of using file cache in php

WBOY
WBOYOriginal
2016-07-25 08:45:221229browse

In web development, file caching can be used to greatly alleviate the pressure on the database. The following code is an example of using file caching in 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. }
Copy code

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. }
Copy code

php


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn