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