Simple PHP cache class


/ Published in: PHP
Save to your folder(s)

A simple class to cache files (or other results) with PHP.


Copy this code and paste it in your HTML
  1. <?php
  2. /**
  3.  * Class Cache
  4.  *
  5.  * @author Koen Ekelschot
  6.  * @license WTFPL
  7.  */
  8. class Cache {
  9.  
  10. private $cachedFile;
  11.  
  12. public function __construct($identifier) {
  13. $this->cachedFile = ROOT.DS.'tmp'.DS.'cache'.DS.md5($identifier);
  14. }
  15.  
  16. public function cacheExists($maxAge) {
  17. if (file_exists($this->cachedFile) && !is_dir($this->cachedFile)) {
  18. if (filemtime($this->cachedFile) + $maxAge > time()) {
  19. return true;
  20. } else {
  21. $this->invalidateCache();
  22. }
  23. }
  24. return false;
  25. }
  26.  
  27. public function getCachedCopy() {
  28. $contents = file_get_contents($this->cachedFile);
  29. return unserialize(base64_decode($contents));
  30. }
  31.  
  32. public function getCachedFilename() {
  33. return str_replace(ROOT, '', $this->cachedFile);
  34. }
  35.  
  36. public function cacheResult($result) {
  37. if (file_exists($this->cachedFile) && !is_dir($this->cachedFile)) {
  38. $this->invalidateCache();
  39. }
  40. $base64 = base64_encode(serialize($result));
  41. file_put_contents($this->cachedFile, $base64);
  42. }
  43.  
  44. private function invalidateCache() {
  45. unlink($this->cachedFile);
  46. }
  47.  
  48. }
  49. ?>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.