CachedPage.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. /**
  3. * Simple cache system, mainly for the RSS/ATOM feeds
  4. */
  5. class CachedPage
  6. {
  7. // Directory containing page caches
  8. private $cacheDir;
  9. // Full URL of the page to cache -typically the value returned by pageUrl()
  10. private $url;
  11. // Should this URL be cached (boolean)?
  12. private $shouldBeCached;
  13. // Name of the cache file for this URL
  14. private $filename;
  15. /**
  16. * Creates a new CachedPage
  17. *
  18. * @param string $cacheDir page cache directory
  19. * @param string $url page URL
  20. * @param bool $shouldBeCached whether this page needs to be cached
  21. */
  22. public function __construct($cacheDir, $url, $shouldBeCached)
  23. {
  24. // TODO: check write access to the cache directory
  25. $this->cacheDir = $cacheDir;
  26. $this->url = $url;
  27. $this->filename = $this->cacheDir.'/'.sha1($url).'.cache';
  28. $this->shouldBeCached = $shouldBeCached;
  29. }
  30. /**
  31. * Returns the cached version of a page, if it exists and should be cached
  32. *
  33. * @return string a cached version of the page if it exists, null otherwise
  34. */
  35. public function cachedVersion()
  36. {
  37. if (!$this->shouldBeCached) {
  38. return null;
  39. }
  40. if (is_file($this->filename)) {
  41. return file_get_contents($this->filename);
  42. }
  43. return null;
  44. }
  45. /**
  46. * Puts a page in the cache
  47. *
  48. * @param string $pageContent XML content to cache
  49. */
  50. public function cache($pageContent)
  51. {
  52. if (!$this->shouldBeCached) {
  53. return;
  54. }
  55. file_put_contents($this->filename, $pageContent);
  56. }
  57. }