file.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. $value = $this->expiration($minutes).serialize($value);
  63. file_put_contents($this->path.$key, $value, LOCK_EX);
  64. }
  65. /**
  66. * Write an item to the cache for five years.
  67. *
  68. * @param string $key
  69. * @param mixed $value
  70. * @return void
  71. */
  72. public function forever($key, $value)
  73. {
  74. return $this->put($key, $value, 2628000);
  75. }
  76. /**
  77. * Delete an item from the cache.
  78. *
  79. * @param string $key
  80. * @return void
  81. */
  82. public function forget($key)
  83. {
  84. if (file_exists($this->path.$key)) @unlink($this->path.$key);
  85. }
  86. }