file.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. <?php namespace Laravel\Cache\Drivers;
  2. class File extends Driver {
  3. /**
  4. * The path to which the cache files should be written.
  5. *
  6. * @var string
  7. */
  8. protected $path;
  9. /**
  10. * Create a new File cache driver instance.
  11. *
  12. * @param string $path
  13. * @return void
  14. */
  15. public function __construct($path)
  16. {
  17. $this->path = $path;
  18. }
  19. /**
  20. * Determine if an item exists in the cache.
  21. *
  22. * @param string $key
  23. * @return bool
  24. */
  25. public function has($key)
  26. {
  27. return ( ! is_null($this->get($key)));
  28. }
  29. /**
  30. * Retrieve an item from the cache driver.
  31. *
  32. * @param string $key
  33. * @return mixed
  34. */
  35. protected function retrieve($key)
  36. {
  37. if ( ! file_exists($this->path.$key)) return null;
  38. // File based caches store have the expiration timestamp stored in
  39. // UNIX format prepended to their contents. We'll compare the
  40. // timestamp to the current time when we read the file.
  41. if (time() >= substr($cache = file_get_contents($this->path.$key), 0, 10))
  42. {
  43. return $this->forget($key);
  44. }
  45. return unserialize(substr($cache, 10));
  46. }
  47. /**
  48. * Write an item to the cache for a given number of minutes.
  49. *
  50. * <code>
  51. * // Put an item in the cache for 15 minutes
  52. * Cache::put('name', 'Taylor', 15);
  53. * </code>
  54. *
  55. * @param string $key
  56. * @param mixed $value
  57. * @param int $minutes
  58. * @return void
  59. */
  60. public function put($key, $value, $minutes)
  61. {
  62. if ($minutes <= 0) return;
  63. $value = $this->expiration($minutes).serialize($value);
  64. file_put_contents($this->path.$key, $value, LOCK_EX);
  65. }
  66. /**
  67. * Write an item to the cache for five years.
  68. *
  69. * @param string $key
  70. * @param mixed $value
  71. * @return void
  72. */
  73. public function forever($key, $value)
  74. {
  75. return $this->put($key, $value, 2628000);
  76. }
  77. /**
  78. * Delete an item from the cache.
  79. *
  80. * @param string $key
  81. * @return void
  82. */
  83. public function forget($key)
  84. {
  85. if (file_exists($this->path.$key)) @unlink($this->path.$key);
  86. }
  87. /**
  88. * Flush the entire cache.
  89. *
  90. * @return void
  91. */
  92. public function flush()
  93. {
  94. array_map('unlink', glob($this->path.'*'));
  95. }
  96. }