cache.class.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. <?php
  2. /**
  3. * Cache for storing data.
  4. *
  5. * @license see /license.txt
  6. * @author Laurent Opprecht <laurent@opprecht.info> for the Univesity of Geneva
  7. */
  8. class Cache
  9. {
  10. /**
  11. * Retrive an item from the cache if item creation date is greater than limit.
  12. * If item does not exists or is stale returns false.
  13. *
  14. * @param any $key
  15. * @param int $limit
  16. * @return false|object
  17. */
  18. static function get($key, $limit = 0)
  19. {
  20. if (!self::has($key, $limit))
  21. {
  22. return false;
  23. }
  24. $path = self::path($key);
  25. return file_get_contents($path);
  26. }
  27. /**
  28. * Returnsn true if the cache has the item and it is not staled.
  29. *
  30. * @param any $key
  31. * @param int $limit
  32. * @return boolean
  33. */
  34. static function has($key, $limit = 0)
  35. {
  36. $path = self::path($key);
  37. if (!is_readable($path))
  38. {
  39. return false;
  40. }
  41. if ($limit)
  42. {
  43. $mtime = filemtime($path);
  44. if ($mtime < $limit)
  45. {
  46. return false;
  47. }
  48. }
  49. return true;
  50. }
  51. /**
  52. * Put something on the cache.
  53. *
  54. * @param any $key
  55. * @param string $value
  56. */
  57. static function put($key, $value)
  58. {
  59. $path = self::path($key);
  60. file_put_contents($path, $value);
  61. }
  62. /**
  63. * Remove an item from the cache.
  64. *
  65. * @param any $key
  66. */
  67. static function remove($key)
  68. {
  69. $path = self::path($key);
  70. if (is_readable($path))
  71. {
  72. unlink($path);
  73. }
  74. }
  75. /**
  76. * Clear the cache. Remove all entries.
  77. */
  78. static function clear()
  79. {
  80. $dir = self::path();
  81. $files = scandir($dir);
  82. $files = array_diff($files, array('.', '..'));
  83. foreach ($files as $file)
  84. {
  85. $path = $dir . $file;
  86. unlink($path);
  87. }
  88. }
  89. /**
  90. * Returns the file path based on the key.
  91. *
  92. * @param any $key
  93. * @return string
  94. */
  95. static function path($key = '')
  96. {
  97. return Chamilo::path('archive/temp/cache/' . self::key($key));
  98. }
  99. /**
  100. * Returns the internal string key from the external key.
  101. * For internal use.
  102. *
  103. * @param any $item
  104. * @return string
  105. */
  106. static function key($item)
  107. {
  108. if (is_object($item))
  109. {
  110. $f = array($item, 'get_unique_id');
  111. if (is_callable($f))
  112. {
  113. return call_user_func($f);
  114. }
  115. }
  116. $result = (string)$item;
  117. }
  118. }