database.php 2.41 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
<?php namespace Laravel\Cache\Drivers;

use Laravel\Config;
use Laravel\Database as DB;
use Laravel\Database\Connection;

class Database extends Driver {

	/**
	 * The cache key from the cache configuration file.
	 *
	 * @var string
	 */
	protected $key;

	/**
	 * Create a new database cache driver instance.
	 *
	 * @param  string  $key
	 * @return void
	 */
	public function __construct($key)
	{
		$this->key = $key;
	}

	/**
	 * Determine if an item exists in the cache.
	 *
	 * @param  string  $key
	 * @return bool
	 */
	public function has($key)
	{
		return ( ! is_null($this->get($key)));
	}

	/**
	 * Retrieve an item from the cache driver.
	 *
	 * @param  string  $key
	 * @return mixed
	 */
	protected function retrieve($key)
	{
		$cache = $this->table()->where('key', '=', $this->key.$key)->first();

		if ( ! is_null($cache))
		{
			if (time() >= $cache->expiration) return $this->forget($key);

			return unserialize($cache->value);
		}
	}

	/**
	 * Write an item to the cache for a given number of minutes.
	 *
	 * <code>
	 *		// Put an item in the cache for 15 minutes
	 *		Cache::put('name', 'Taylor', 15);
	 * </code>
	 *
	 * @param  string  $key
	 * @param  mixed   $value
	 * @param  int     $minutes
	 * @return void
	 */
	public function put($key, $value, $minutes)
	{
		$key = $this->key.$key;

		$value = serialize($value);

		$expiration = $this->expiration($minutes);

		// To update the value, we'll first attempt an insert against the
		// database and if we catch an exception, we'll assume that the
		// primary key already exists in the table and update.
		try
		{
			$this->table()->insert(compact('key', 'value', 'expiration'));
		}
		catch (\Exception $e)
		{
			$this->table()->where('key', '=', $key)->update(compact('value', 'expiration'));
		}
	}

	/**
91 92 93 94 95 96 97 98 99 100 101 102
	 * 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);
	}

	/**
103 104 105 106 107 108 109 110 111 112 113 114 115
	 * Delete an item from the cache.
	 *
	 * @param  string  $key
	 * @return void
	 */
	public function forget($key)
	{
		$this->table()->where('key', '=', $this->key.$key)->delete();
	}

	/**
	 * Get a query builder for the database table.
	 *
Phill Sparks committed
116
	 * @return Laravel\Database\Query
117 118 119 120 121 122 123 124 125
	 */
	protected function table()
	{
		$connection = DB::connection(Config::get('cache.database.connection'));

		return $connection->table(Config::get('cache.database.table'));
	}

}