Posted By

peckham on 10/14/12


Tagged

class php simple cache


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

gecube


Simple PHP cache class


 / Published in: PHP
 

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

  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  

You need to login to post a comment.