ExpiringCache.php 1.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. /*
  3. * This file is part of the Assetic package, an OpenSky project.
  4. *
  5. * (c) 2010-2011 OpenSky Project Inc
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Assetic\Cache;
  11. /**
  12. * Adds expiration to a cache backend.
  13. *
  14. * @author Kris Wallsmith <kris.wallsmith@gmail.com>
  15. */
  16. class ExpiringCache implements CacheInterface
  17. {
  18. private $cache;
  19. private $lifetime;
  20. public function __construct(CacheInterface $cache, $lifetime)
  21. {
  22. $this->cache = $cache;
  23. $this->lifetime = $lifetime;
  24. }
  25. public function has($key)
  26. {
  27. if ($this->cache->has($key)) {
  28. if (time() < $this->cache->get($key.'.expires')) {
  29. return true;
  30. }
  31. $this->cache->remove($key.'.expires');
  32. $this->cache->remove($key);
  33. }
  34. return false;
  35. }
  36. public function get($key)
  37. {
  38. return $this->cache->get($key);
  39. }
  40. public function set($key, $value)
  41. {
  42. $this->cache->set($key.'.expires', time() + $this->lifetime);
  43. $this->cache->set($key, $value);
  44. }
  45. public function remove($key)
  46. {
  47. $this->cache->remove($key.'.expires');
  48. $this->cache->remove($key);
  49. }
  50. }