Cache.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. namespace System\Models;
  3. class Cache
  4. {
  5. private $cachePath;
  6. public function __construct()
  7. {
  8. $cachePath = getcwd() . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  9. if(!is_dir($cachePath)){
  10. mkdir($cachePath, 0774, true) or die('Please create a cache folder in your root and make it writable.');
  11. }
  12. is_writable($cachePath) or die('Your cache folder is not writable.');
  13. $this->cachePath = $cachePath;
  14. }
  15. public function validate()
  16. {
  17. if(isset($_SERVER['HTTP_CACHE_CONTROL']) && $_SERVER['HTTP_CACHE_CONTROL'] == 'max-age=0')
  18. {
  19. return false;
  20. }
  21. $requestFile = $this->cachePath.'request.txt';
  22. if(!file_exists($requestFile))
  23. {
  24. $this->writeFile($requestFile, time());
  25. return false;
  26. }
  27. $lastRequest = file_get_contents($requestFile);
  28. if(time() - $lastRequest > 600)
  29. {
  30. return false;
  31. }
  32. return true;
  33. }
  34. public function refresh($data, $name)
  35. {
  36. $sData = serialize($data);
  37. $dataFile = $this->cachePath.$name.'.txt';
  38. $requestFile = $this->cachePath.'request.txt';
  39. $this->writeFile($dataFile, $sData);
  40. $this->writeFile($requestFile, time());
  41. }
  42. public function getData($name)
  43. {
  44. if (file_exists($this->cachePath.$name.'.txt'))
  45. {
  46. $data = file_get_contents($this->cachePath.$name.'.txt');
  47. $data = unserialize($data);
  48. return $data;
  49. }
  50. return false;
  51. }
  52. public function clearData($name)
  53. {
  54. /* todo */
  55. }
  56. public function clearAll()
  57. {
  58. /* todo */
  59. }
  60. public function writeFile($file, $data)
  61. {
  62. $fp = fopen($file, "w");
  63. fwrite($fp, $data);
  64. fclose($fp);
  65. }
  66. }
  67. ?>