Heim  >  Artikel  >  Backend-Entwicklung  >  php中使用文件缓存的例子

php中使用文件缓存的例子

WBOY
WBOYOriginal
2016-07-25 08:45:221254Durchsuche

在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


Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn