file.php 1.71 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 45 46 47 48
		// File based caches store have the expiration timestamp stored in
		// UNIX format prepended to their contents. This timestamp is then
		// extracted and removed when the cache is read to determine if
		// the file is still valid.
		if (time() >= substr($cache = file_get_contents($this->path.$key), 0, 10))
Taylor Otwell committed
49
		{
Taylor Otwell committed
50
			return $this->forget($key);
Taylor Otwell committed
51 52
		}

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

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

Taylor Otwell committed
74 75 76 77 78 79
	/**
	 * Delete an item from the cache.
	 *
	 * @param  string  $key
	 * @return void
	 */
Taylor Otwell committed
80 81
	public function forget($key)
	{
82 83 84 85
		if (file_exists($this->path.$key))
		{
			@unlink($this->path.$key);
		}
Taylor Otwell committed
86 87 88
	}

}