file.php 1.92 KB
Newer Older
1
<?php namespace Laravel\Cache\Drivers;
Taylor Otwell committed
2

3
class File extends Driver {
4 5

	/**
6 7 8 9
	 * The path to which the cache files should be written.
	 *
	 * @var string
	 */
10
	protected $path;
11 12

	/**
13 14
	 * Create a new File cache driver instance.
	 *
15
	 * @param  string  $path
16 17
	 * @return void
	 */
18
	public function __construct($path)
19
	{
20
		$this->path = $path;
21 22 23
	}

	/**
Taylor Otwell committed
24 25 26 27 28
	 * Determine if an item exists in the cache.
	 *
	 * @param  string  $key
	 * @return bool
	 */
Taylor Otwell committed
29 30 31 32 33
	public function has($key)
	{
		return ( ! is_null($this->get($key)));
	}

Taylor Otwell committed
34 35 36 37 38 39 40
	/**
	 * Retrieve an item from the cache driver.
	 *
	 * @param  string  $key
	 * @return mixed
	 */
	protected function retrieve($key)
Taylor Otwell committed
41
	{
42
		if ( ! file_exists($this->path.$key)) return null;
Taylor Otwell committed
43

44
		// File based caches store have the expiration timestamp stored in
Taylor Otwell committed
45 46
		// UNIX format prepended to their contents. We'll compare the
		// timestamp to the current time when we read the file.
47
		if (time() >= substr($cache = file_get_contents($this->path.$key), 0, 10))
Taylor Otwell committed
48
		{
Taylor Otwell committed
49
			return $this->forget($key);
Taylor Otwell committed
50 51
		}

Taylor Otwell committed
52
		return unserialize(substr($cache, 10));
Taylor Otwell committed
53 54
	}

Taylor Otwell committed
55 56 57
	/**
	 * Write an item to the cache for a given number of minutes.
	 *
58 59 60 61 62
	 * <code>
	 *		// Put an item in the cache for 15 minutes
	 *		Cache::put('name', 'Taylor', 15);
	 * </code>
	 *
Taylor Otwell committed
63 64 65 66 67
	 * @param  string  $key
	 * @param  mixed   $value
	 * @param  int     $minutes
	 * @return void
	 */
Taylor Otwell committed
68 69
	public function put($key, $value, $minutes)
	{
70 71
		if ($minutes <= 0) return;

72
		$value = $this->expiration($minutes).serialize($value);
73 74

		file_put_contents($this->path.$key, $value, LOCK_EX);
Taylor Otwell committed
75 76
	}

Taylor Otwell committed
77
	/**
78 79 80 81 82 83 84 85 86 87 88 89
	 * Write an item to the cache for five years.
	 *
	 * @param  string  $key
	 * @param  mixed   $value
	 * @return void
	 */
	public function forever($key, $value)
	{
		return $this->put($key, $value, 2628000);
	}

	/**
Taylor Otwell committed
90 91 92 93 94
	 * Delete an item from the cache.
	 *
	 * @param  string  $key
	 * @return void
	 */
Taylor Otwell committed
95 96
	public function forget($key)
	{
97
		if (file_exists($this->path.$key)) @unlink($this->path.$key);
Taylor Otwell committed
98 99 100
	}

}