1: <?php
2: /**
3: * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
4: * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
5: *
6: * Licensed under The MIT License
7: * Redistributions of files must retain the above copyright notice.
8: *
9: * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
10: * @link http://cakephp.org CakePHP(tm) Project
11: * @package Cake.Cache
12: * @since CakePHP(tm) v 1.2.0.4933
13: * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
14: */
15:
16: App::uses('Inflector', 'Utility');
17: App::uses('CacheEngine', 'Cache');
18:
19: /**
20: * Cache provides a consistent interface to Caching in your application. It allows you
21: * to use several different Cache engines, without coupling your application to a specific
22: * implementation. It also allows you to change out cache storage or configuration without effecting
23: * the rest of your application.
24: *
25: * You can configure Cache engines in your application's `bootstrap.php` file. A sample configuration would
26: * be
27: *
28: * {{{
29: * Cache::config('shared', array(
30: * 'engine' => 'Apc',
31: * 'prefix' => 'my_app_'
32: * ));
33: * }}}
34: *
35: * This would configure an APC cache engine to the 'shared' alias. You could then read and write
36: * to that cache alias by using it for the `$config` parameter in the various Cache methods. In
37: * general all Cache operations are supported by all cache engines. However, Cache::increment() and
38: * Cache::decrement() are not supported by File caching.
39: *
40: * @package Cake.Cache
41: */
42: class Cache {
43:
44: /**
45: * Cache configuration stack
46: * Keeps the permanent/default settings for each cache engine.
47: * These settings are used to reset the engines after temporary modification.
48: *
49: * @var array
50: */
51: protected static $_config = array();
52:
53: /**
54: * Whether to reset the settings with the next call to Cache::set();
55: *
56: * @var array
57: */
58: protected static $_reset = false;
59:
60: /**
61: * Engine instances keyed by configuration name.
62: *
63: * @var array
64: */
65: protected static $_engines = array();
66:
67: /**
68: * Set the cache configuration to use. config() can
69: * both create new configurations, return the settings for already configured
70: * configurations.
71: *
72: * To create a new configuration, or to modify an existing configuration permanently:
73: *
74: * `Cache::config('my_config', array('engine' => 'File', 'path' => TMP));`
75: *
76: * If you need to modify a configuration temporarily, use Cache::set().
77: * To get the settings for a configuration:
78: *
79: * `Cache::config('default');`
80: *
81: * There are 5 built-in caching engines:
82: *
83: * - `FileEngine` - Uses simple files to store content. Poor performance, but good for
84: * storing large objects, or things that are not IO sensitive.
85: * - `ApcEngine` - Uses the APC object cache, one of the fastest caching engines.
86: * - `MemcacheEngine` - Uses the PECL::Memcache extension and Memcached for storage.
87: * Fast reads/writes, and benefits from memcache being distributed.
88: * - `XcacheEngine` - Uses the Xcache extension, an alternative to APC.
89: * - `WincacheEngine` - Uses Windows Cache Extension for PHP. Supports wincache 1.1.0 and higher.
90: *
91: * The following keys are used in core cache engines:
92: *
93: * - `duration` Specify how long items in this cache configuration last.
94: * - `groups` List of groups or 'tags' associated to every key stored in this config.
95: * handy for deleting a complete group from cache.
96: * - `prefix` Prefix appended to all entries. Good for when you need to share a keyspace
97: * with either another cache config or another application.
98: * - `probability` Probability of hitting a cache gc cleanup. Setting to 0 will disable
99: * cache::gc from ever being called automatically.
100: * - `servers' Used by memcache. Give the address of the memcached servers to use.
101: * - `compress` Used by memcache. Enables memcache's compressed format.
102: * - `serialize` Used by FileCache. Should cache objects be serialized first.
103: * - `path` Used by FileCache. Path to where cachefiles should be saved.
104: * - `lock` Used by FileCache. Should files be locked before writing to them?
105: * - `user` Used by Xcache. Username for XCache
106: * - `password` Used by Xcache. Password for XCache
107: *
108: * @see app/Config/core.php for configuration settings
109: * @param string $name Name of the configuration
110: * @param array $settings Optional associative array of settings passed to the engine
111: * @return array(engine, settings) on success, false on failure
112: * @throws CacheException
113: */
114: public static function config($name = null, $settings = array()) {
115: if (is_array($name)) {
116: $settings = $name;
117: }
118:
119: $current = array();
120: if (isset(self::$_config[$name])) {
121: $current = self::$_config[$name];
122: }
123:
124: if (!empty($settings)) {
125: self::$_config[$name] = array_merge($current, $settings);
126: }
127:
128: if (empty(self::$_config[$name]['engine'])) {
129: return false;
130: }
131:
132: $engine = self::$_config[$name]['engine'];
133:
134: if (!isset(self::$_engines[$name])) {
135: self::_buildEngine($name);
136: $settings = self::$_config[$name] = self::settings($name);
137: } elseif ($settings = self::set(self::$_config[$name], null, $name)) {
138: self::$_config[$name] = $settings;
139: }
140: return compact('engine', 'settings');
141: }
142:
143: /**
144: * Finds and builds the instance of the required engine class.
145: *
146: * @param string $name Name of the config array that needs an engine instance built
147: * @return boolean
148: * @throws CacheException
149: */
150: protected static function _buildEngine($name) {
151: $config = self::$_config[$name];
152:
153: list($plugin, $class) = pluginSplit($config['engine'], true);
154: $cacheClass = $class . 'Engine';
155: App::uses($cacheClass, $plugin . 'Cache/Engine');
156: if (!class_exists($cacheClass)) {
157: return false;
158: }
159: $cacheClass = $class . 'Engine';
160: if (!is_subclass_of($cacheClass, 'CacheEngine')) {
161: throw new CacheException(__d('cake_dev', 'Cache engines must use CacheEngine as a base class.'));
162: }
163: self::$_engines[$name] = new $cacheClass();
164: if (self::$_engines[$name]->init($config)) {
165: if (self::$_engines[$name]->settings['probability'] && time() % self::$_engines[$name]->settings['probability'] === 0) {
166: self::$_engines[$name]->gc();
167: }
168: return true;
169: }
170: return false;
171: }
172:
173: /**
174: * Returns an array containing the currently configured Cache settings.
175: *
176: * @return array Array of configured Cache config names.
177: */
178: public static function configured() {
179: return array_keys(self::$_config);
180: }
181:
182: /**
183: * Drops a cache engine. Deletes the cache configuration information
184: * If the deleted configuration is the last configuration using an certain engine,
185: * the Engine instance is also unset.
186: *
187: * @param string $name A currently configured cache config you wish to remove.
188: * @return boolean success of the removal, returns false when the config does not exist.
189: */
190: public static function drop($name) {
191: if (!isset(self::$_config[$name])) {
192: return false;
193: }
194: unset(self::$_config[$name], self::$_engines[$name]);
195: return true;
196: }
197:
198: /**
199: * Temporarily change the settings on a cache config. The settings will persist for the next write
200: * operation (write, decrement, increment, clear). Any reads that are done before the write, will
201: * use the modified settings. If `$settings` is empty, the settings will be reset to the
202: * original configuration.
203: *
204: * Can be called with 2 or 3 parameters. To set multiple values at once.
205: *
206: * `Cache::set(array('duration' => '+30 minutes'), 'my_config');`
207: *
208: * Or to set one value.
209: *
210: * `Cache::set('duration', '+30 minutes', 'my_config');`
211: *
212: * To reset a config back to the originally configured values.
213: *
214: * `Cache::set(null, 'my_config');`
215: *
216: * @param string|array $settings Optional string for simple name-value pair or array
217: * @param string $value Optional for a simple name-value pair
218: * @param string $config The configuration name you are changing. Defaults to 'default'
219: * @return array Array of settings.
220: */
221: public static function set($settings = array(), $value = null, $config = 'default') {
222: if (is_array($settings) && $value !== null) {
223: $config = $value;
224: }
225: if (!isset(self::$_config[$config]) || !isset(self::$_engines[$config])) {
226: return false;
227: }
228: if (!empty($settings)) {
229: self::$_reset = true;
230: }
231:
232: if (self::$_reset === true) {
233: if (empty($settings)) {
234: self::$_reset = false;
235: $settings = self::$_config[$config];
236: } else {
237: if (is_string($settings) && $value !== null) {
238: $settings = array($settings => $value);
239: }
240: $settings = array_merge(self::$_config[$config], $settings);
241: if (isset($settings['duration']) && !is_numeric($settings['duration'])) {
242: $settings['duration'] = strtotime($settings['duration']) - time();
243: }
244: }
245: self::$_engines[$config]->settings = $settings;
246: }
247: return self::settings($config);
248: }
249:
250: /**
251: * Garbage collection
252: *
253: * Permanently remove all expired and deleted data
254: *
255: * @param string $config [optional] The config name you wish to have garbage collected. Defaults to 'default'
256: * @param integer $expires [optional] An expires timestamp. Defaults to NULL
257: * @return void
258: */
259: public static function gc($config = 'default', $expires = null) {
260: self::$_engines[$config]->gc($expires);
261: }
262:
263: /**
264: * Write data for key into cache. Will automatically use the currently
265: * active cache configuration. To set the currently active configuration use
266: * Cache::config()
267: *
268: * ### Usage:
269: *
270: * Writing to the active cache config:
271: *
272: * `Cache::write('cached_data', $data);`
273: *
274: * Writing to a specific cache config:
275: *
276: * `Cache::write('cached_data', $data, 'long_term');`
277: *
278: * @param string $key Identifier for the data
279: * @param mixed $value Data to be cached - anything except a resource
280: * @param string $config Optional string configuration name to write to. Defaults to 'default'
281: * @return boolean True if the data was successfully cached, false on failure
282: */
283: public static function write($key, $value, $config = 'default') {
284: $settings = self::settings($config);
285:
286: if (empty($settings)) {
287: return false;
288: }
289: if (!self::isInitialized($config)) {
290: return false;
291: }
292: $key = self::$_engines[$config]->key($key);
293:
294: if (!$key || is_resource($value)) {
295: return false;
296: }
297:
298: $success = self::$_engines[$config]->write($settings['prefix'] . $key, $value, $settings['duration']);
299: self::set(null, $config);
300: if ($success === false && $value !== '') {
301: trigger_error(
302: __d('cake_dev',
303: "%s cache was unable to write '%s' to %s cache",
304: $config,
305: $key,
306: self::$_engines[$config]->settings['engine']
307: ),
308: E_USER_WARNING
309: );
310: }
311: return $success;
312: }
313:
314: /**
315: * Read a key from the cache. Will automatically use the currently
316: * active cache configuration. To set the currently active configuration use
317: * Cache::config()
318: *
319: * ### Usage:
320: *
321: * Reading from the active cache configuration.
322: *
323: * `Cache::read('my_data');`
324: *
325: * Reading from a specific cache configuration.
326: *
327: * `Cache::read('my_data', 'long_term');`
328: *
329: * @param string $key Identifier for the data
330: * @param string $config optional name of the configuration to use. Defaults to 'default'
331: * @return mixed The cached data, or false if the data doesn't exist, has expired, or if there was an error fetching it
332: */
333: public static function read($key, $config = 'default') {
334: $settings = self::settings($config);
335:
336: if (empty($settings)) {
337: return false;
338: }
339: if (!self::isInitialized($config)) {
340: return false;
341: }
342: $key = self::$_engines[$config]->key($key);
343: if (!$key) {
344: return false;
345: }
346: return self::$_engines[$config]->read($settings['prefix'] . $key);
347: }
348:
349: /**
350: * Increment a number under the key and return incremented value.
351: *
352: * @param string $key Identifier for the data
353: * @param integer $offset How much to add
354: * @param string $config Optional string configuration name. Defaults to 'default'
355: * @return mixed new value, or false if the data doesn't exist, is not integer,
356: * or if there was an error fetching it.
357: */
358: public static function increment($key, $offset = 1, $config = 'default') {
359: $settings = self::settings($config);
360:
361: if (empty($settings)) {
362: return false;
363: }
364: if (!self::isInitialized($config)) {
365: return false;
366: }
367: $key = self::$_engines[$config]->key($key);
368:
369: if (!$key || !is_integer($offset) || $offset < 0) {
370: return false;
371: }
372: $success = self::$_engines[$config]->increment($settings['prefix'] . $key, $offset);
373: self::set(null, $config);
374: return $success;
375: }
376:
377: /**
378: * Decrement a number under the key and return decremented value.
379: *
380: * @param string $key Identifier for the data
381: * @param integer $offset How much to subtract
382: * @param string $config Optional string configuration name. Defaults to 'default'
383: * @return mixed new value, or false if the data doesn't exist, is not integer,
384: * or if there was an error fetching it
385: */
386: public static function decrement($key, $offset = 1, $config = 'default') {
387: $settings = self::settings($config);
388:
389: if (empty($settings)) {
390: return false;
391: }
392: if (!self::isInitialized($config)) {
393: return false;
394: }
395: $key = self::$_engines[$config]->key($key);
396:
397: if (!$key || !is_integer($offset) || $offset < 0) {
398: return false;
399: }
400: $success = self::$_engines[$config]->decrement($settings['prefix'] . $key, $offset);
401: self::set(null, $config);
402: return $success;
403: }
404:
405: /**
406: * Delete a key from the cache.
407: *
408: * ### Usage:
409: *
410: * Deleting from the active cache configuration.
411: *
412: * `Cache::delete('my_data');`
413: *
414: * Deleting from a specific cache configuration.
415: *
416: * `Cache::delete('my_data', 'long_term');`
417: *
418: * @param string $key Identifier for the data
419: * @param string $config name of the configuration to use. Defaults to 'default'
420: * @return boolean True if the value was successfully deleted, false if it didn't exist or couldn't be removed
421: */
422: public static function delete($key, $config = 'default') {
423: $settings = self::settings($config);
424:
425: if (empty($settings)) {
426: return false;
427: }
428: if (!self::isInitialized($config)) {
429: return false;
430: }
431: $key = self::$_engines[$config]->key($key);
432: if (!$key) {
433: return false;
434: }
435:
436: $success = self::$_engines[$config]->delete($settings['prefix'] . $key);
437: self::set(null, $config);
438: return $success;
439: }
440:
441: /**
442: * Delete all keys from the cache.
443: *
444: * @param boolean $check if true will check expiration, otherwise delete all
445: * @param string $config name of the configuration to use. Defaults to 'default'
446: * @return boolean True if the cache was successfully cleared, false otherwise
447: */
448: public static function clear($check = false, $config = 'default') {
449: if (!self::isInitialized($config)) {
450: return false;
451: }
452: $success = self::$_engines[$config]->clear($check);
453: self::set(null, $config);
454: return $success;
455: }
456:
457: /**
458: * Delete all keys from the cache belonging to the same group.
459: *
460: * @param string $group name of the group to be cleared
461: * @param string $config name of the configuration to use. Defaults to 'default'
462: * @return boolean True if the cache group was successfully cleared, false otherwise
463: */
464: public static function clearGroup($group, $config = 'default') {
465: if (!self::isInitialized($config)) {
466: return false;
467: }
468: $success = self::$_engines[$config]->clearGroup($group);
469: self::set(null, $config);
470: return $success;
471: }
472:
473: /**
474: * Check if Cache has initialized a working config for the given name.
475: *
476: * @param string $config name of the configuration to use. Defaults to 'default'
477: * @return boolean Whether or not the config name has been initialized.
478: */
479: public static function isInitialized($config = 'default') {
480: if (Configure::read('Cache.disable')) {
481: return false;
482: }
483: return isset(self::$_engines[$config]);
484: }
485:
486: /**
487: * Return the settings for the named cache engine.
488: *
489: * @param string $name Name of the configuration to get settings for. Defaults to 'default'
490: * @return array list of settings for this engine
491: * @see Cache::config()
492: */
493: public static function settings($name = 'default') {
494: if (!empty(self::$_engines[$name])) {
495: return self::$_engines[$name]->settings();
496: }
497: return array();
498: }
499:
500: }
501:
502: