CachedPage.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. // Should this URL be cached (boolean)?
  10. private $shouldBeCached;
  11. // Name of the cache file for this URL
  12. private $filename;
  13. /**
  14. * Creates a new CachedPage
  15. *
  16. * @param string $cacheDir page cache directory
  17. * @param string $url page URL
  18. * @param bool $shouldBeCached whether this page needs to be cached
  19. */
  20. public function __construct($cacheDir, $url, $shouldBeCached)
  21. {
  22. // TODO: check write access to the cache directory
  23. $this->cacheDir = $cacheDir;
  24. $this->filename = $this->cacheDir.'/'.sha1($url).'.cache';
  25. $this->shouldBeCached = $shouldBeCached;
  26. }
  27. /**
  28. * Returns the cached version of a page, if it exists and should be cached
  29. *
  30. * @return string a cached version of the page if it exists, null otherwise
  31. */
  32. public function cachedVersion()
  33. {
  34. if (!$this->shouldBeCached) {
  35. return null;
  36. }
  37. if (is_file($this->filename)) {
  38. return file_get_contents($this->filename);
  39. }
  40. return null;
  41. }
  42. /**
  43. * Puts a page in the cache
  44. *
  45. * @param string $pageContent XML content to cache
  46. */
  47. public function cache($pageContent)
  48. {
  49. if (!$this->shouldBeCached) {
  50. return;
  51. }
  52. file_put_contents($this->filename, $pageContent);
  53. }
  54. }