1: <?php namespace Laravel\Cache\Drivers;
2:
3: use Laravel\Config;
4: use Laravel\Database as DB;
5: use Laravel\Database\Connection;
6:
7: class Database extends Driver {
8:
9: /**
10: * The cache key from the cache configuration file.
11: *
12: * @var string
13: */
14: protected $key;
15:
16: /**
17: * Create a new database cache driver instance.
18: *
19: * @param string $key
20: * @return void
21: */
22: public function __construct($key)
23: {
24: $this->key = $key;
25: }
26:
27: /**
28: * Determine if an item exists in the cache.
29: *
30: * @param string $key
31: * @return bool
32: */
33: public function has($key)
34: {
35: return ( ! is_null($this->get($key)));
36: }
37:
38: /**
39: * Retrieve an item from the cache driver.
40: *
41: * @param string $key
42: * @return mixed
43: */
44: protected function retrieve($key)
45: {
46: $cache = $this->table()->where('key', '=', $this->key.$key)->first();
47:
48: if ( ! is_null($cache))
49: {
50: if (time() >= $cache->expiration) return $this->forget($key);
51:
52: return unserialize($cache->value);
53: }
54: }
55:
56: /**
57: * Write an item to the cache for a given number of minutes.
58: *
59: * <code>
60: * // Put an item in the cache for 15 minutes
61: * Cache::put('name', 'Taylor', 15);
62: * </code>
63: *
64: * @param string $key
65: * @param mixed $value
66: * @param int $minutes
67: * @return void
68: */
69: public function put($key, $value, $minutes)
70: {
71: $key = $this->key.$key;
72:
73: $value = serialize($value);
74:
75: $expiration = $this->expiration($minutes);
76:
77: // To update the value, we'll first attempt an insert against the
78: // database and if we catch an exception we'll assume that the
79: // primary key already exists in the table and update.
80: try
81: {
82: $this->table()->insert(compact('key', 'value', 'expiration'));
83: }
84: catch (\Exception $e)
85: {
86: $this->table()->where('key', '=', $key)->update(compact('value', 'expiration'));
87: }
88: }
89:
90: /**
91: * Write an item to the cache for five years.
92: *
93: * @param string $key
94: * @param mixed $value
95: * @return void
96: */
97: public function forever($key, $value)
98: {
99: return $this->put($key, $value, 2628000);
100: }
101:
102: /**
103: * Delete an item from the cache.
104: *
105: * @param string $key
106: * @return void
107: */
108: public function forget($key)
109: {
110: $this->table()->where('key', '=', $this->key.$key)->delete();
111: }
112:
113: /**
114: * Get a query builder for the database table.
115: *
116: * @return Laravel\Database\Query
117: */
118: protected function table()
119: {
120: $connection = DB::connection(Config::get('cache.database.connection'));
121:
122: return $connection->table(Config::get('cache.database.table'));
123: }
124:
125: }