file.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php namespace System\Cache\Driver;
  2. class File implements \System\Cache\Driver {
  3. /**
  4. * All of the loaded cache items.
  5. *
  6. * @var array
  7. */
  8. private $items = array();
  9. /**
  10. * Determine if an item exists in the cache.
  11. *
  12. * @param string $key
  13. * @return bool
  14. */
  15. public function has($key)
  16. {
  17. return ( ! is_null($this->get($key)));
  18. }
  19. /**
  20. * Get an item from the cache.
  21. *
  22. * @param string $key
  23. * @param mixed $default
  24. * @return mixed
  25. */
  26. public function get($key, $default = null)
  27. {
  28. // --------------------------------------------------
  29. // If the item has already been loaded, return it.
  30. // --------------------------------------------------
  31. if (array_key_exists($key, $this->items))
  32. {
  33. return $this->items[$key];
  34. }
  35. // --------------------------------------------------
  36. // Does the cache item even exist?
  37. // --------------------------------------------------
  38. if ( ! file_exists(APP_PATH.'cache/'.$key))
  39. {
  40. return $default;
  41. }
  42. $cache = file_get_contents(APP_PATH.'cache/'.$key);
  43. // --------------------------------------------------
  44. // Has the cache expired? The UNIX expiration time
  45. // is stored at the beginning of the file.
  46. // --------------------------------------------------
  47. if (time() >= substr($cache, 0, 10))
  48. {
  49. $this->forget($key);
  50. return $default;
  51. }
  52. return $this->items[$key] = unserialize(substr($cache, 10));
  53. }
  54. /**
  55. * Write an item to the cache.
  56. *
  57. * @param string $key
  58. * @param mixed $value
  59. * @param int $minutes
  60. * @return void
  61. */
  62. public function put($key, $value, $minutes)
  63. {
  64. file_put_contents(APP_PATH.'cache/'.$key, (time() + ($minutes * 60)).serialize($value), LOCK_EX);
  65. }
  66. /**
  67. * Delete an item from the cache.
  68. *
  69. * @param string $key
  70. * @return void
  71. */
  72. public function forget($key)
  73. {
  74. @unlink(APP_PATH.'cache/'.$key);
  75. }
  76. }