1: <?php
2: /**
3: * Caching for CakePHP.
4: *
5: *
6: * PHP 5
7: *
8: * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
9: * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
10: *
11: * Licensed under The MIT License
12: * Redistributions of files must retain the above copyright notice.
13: *
14: * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
15: * @link http://cakephp.org CakePHP(tm) Project
16: * @package Cake.Cache
17: * @since CakePHP(tm) v 1.2.0.4933
18: * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
19: */
20:
21: App::uses('Inflector', 'Utility');
22:
23: /**
24: * Cache provides a consistent interface to Caching in your application. It allows you
25: * to use several different Cache engines, without coupling your application to a specific
26: * implementation. It also allows you to change out cache storage or configuration without effecting
27: * the rest of your application.
28: *
29: * You can configure Cache engines in your application's `bootstrap.php` file. A sample configuration would
30: * be
31: *
32: * {{{
33: * Cache::config('shared', array(
34: * 'engine' => 'Apc',
35: * 'prefix' => 'my_app_'
36: * ));
37: * }}}
38: *
39: * This would configure an APC cache engine to the 'shared' alias. You could then read and write
40: * to that cache alias by using it for the `$config` parameter in the various Cache methods. In
41: * general all Cache operations are supported by all cache engines. However, Cache::increment() and
42: * Cache::decrement() are not supported by File caching.
43: *
44: * @package Cake.Cache
45: */
46: class Cache {
47:
48: /**
49: * Cache configuration stack
50: * Keeps the permanent/default settings for each cache engine.
51: * These settings are used to reset the engines after temporary modification.
52: *
53: * @var array
54: */
55: protected static $_config = array();
56:
57: /**
58: * Whether to reset the settings with the next call to Cache::set();
59: *
60: * @var array
61: */
62: protected static $_reset = false;
63:
64: /**
65: * Engine instances keyed by configuration name.
66: *
67: * @var array
68: */
69: protected static $_engines = array();
70:
71: /**
72: * Set the cache configuration to use. config() can
73: * both create new configurations, return the settings for already configured
74: * configurations.
75: *
76: * To create a new configuration, or to modify an existing configuration permanently:
77: *
78: * `Cache::config('my_config', array('engine' => 'File', 'path' => TMP));`
79: *
80: * If you need to modify a configuration temporarily, use Cache::set().
81: * To get the settings for a configuration:
82: *
83: * `Cache::config('default');`
84: *
85: * There are 5 built-in caching engines:
86: *
87: * - `FileEngine` - Uses simple files to store content. Poor performance, but good for
88: * storing large objects, or things that are not IO sensitive.
89: * - `ApcEngine` - Uses the APC object cache, one of the fastest caching engines.
90: * - `MemcacheEngine` - Uses the PECL::Memcache extension and Memcached for storage.
91: * Fast reads/writes, and benefits from memcache being distributed.
92: * - `XcacheEngine` - Uses the Xcache extension, an alternative to APC.
93: * - `WincacheEngine` - Uses Windows Cache Extension for PHP. Supports wincache 1.1.0 and higher.
94: *
95: * The following keys are used in core cache engines:
96: *
97: * - `duration` Specify how long items in this cache configuration last.
98: * - `prefix` Prefix appended to all entries. Good for when you need to share a keyspace
99: * with either another cache config or another application.
100: * - `probability` Probability of hitting a cache gc cleanup. Setting to 0 will disable
101: * cache::gc from ever being called automatically.
102: * - `servers' Used by memcache. Give the address of the memcached servers to use.
103: * - `compress` Used by memcache. Enables memcache's compressed format.
104: * - `serialize` Used by FileCache. Should cache objects be serialized first.
105: * - `path` Used by FileCache. Path to where cachefiles should be saved.
106: * - `lock` Used by FileCache. Should files be locked before writing to them?
107: * - `user` Used by Xcache. Username for XCache
108: * - `password` Used by Xcache. Password for XCache
109: *
110: * @see app/Config/core.php for configuration settings
111: * @param string $name Name of the configuration
112: * @param array $settings Optional associative array of settings passed to the engine
113: * @return array(engine, settings) on success, false on failure
114: * @throws CacheException
115: */
116: public static function config($name = null, $settings = array()) {
117: if (is_array($name)) {
118: $settings = $name;
119: }
120:
121: $current = array();
122: if (isset(self::$_config[$name])) {
123: $current = self::$_config[$name];
124: }
125:
126: if (!empty($settings)) {
127: self::$_config[$name] = array_merge($current, $settings);
128: }
129:
130: if (empty(self::$_config[$name]['engine'])) {
131: return false;
132: }
133:
134: $engine = self::$_config[$name]['engine'];
135:
136: if (!isset(self::$_engines[$name])) {
137: self::_buildEngine($name);
138: $settings = self::$_config[$name] = self::settings($name);
139: } elseif ($settings = self::set(self::$_config[$name], null, $name)) {
140: self::$_config[$name] = $settings;
141: }
142: return compact('engine', 'settings');
143: }
144:
145: /**
146: * Finds and builds the instance of the required engine class.
147: *
148: * @param string $name Name of the config array that needs an engine instance built
149: * @return boolean
150: * @throws CacheException
151: */
152: protected static function _buildEngine($name) {
153: $config = self::$_config[$name];
154:
155: list($plugin, $class) = pluginSplit($config['engine'], true);
156: $cacheClass = $class . 'Engine';
157: App::uses($cacheClass, $plugin . 'Cache/Engine');
158: if (!class_exists($cacheClass)) {
159: return false;
160: }
161: $cacheClass = $class . 'Engine';
162: if (!is_subclass_of($cacheClass, 'CacheEngine')) {
163: throw new CacheException(__d('cake_dev', 'Cache engines must use CacheEngine as a base class.'));
164: }
165: self::$_engines[$name] = new $cacheClass();
166: if (self::$_engines[$name]->init($config)) {
167: if (self::$_engines[$name]->settings['probability'] && time() % self::$_engines[$name]->settings['probability'] === 0) {
168: self::$_engines[$name]->gc();
169: }
170: return true;
171: }
172: return false;
173: }
174:
175: /**
176: * Returns an array containing the currently configured Cache settings.
177: *
178: * @return array Array of configured Cache config names.
179: */
180: public static function configured() {
181: return array_keys(self::$_config);
182: }
183:
184: /**
185: * Drops a cache engine. Deletes the cache configuration information
186: * If the deleted configuration is the last configuration using an certain engine,
187: * the Engine instance is also unset.
188: *
189: * @param string $name A currently configured cache config you wish to remove.
190: * @return boolean success of the removal, returns false when the config does not exist.
191: */
192: public static function drop($name) {
193: if (!isset(self::$_config[$name])) {
194: return false;
195: }
196: unset(self::$_config[$name], self::$_engines[$name]);
197: return true;
198: }
199:
200: /**
201: * Temporarily change the settings on a cache config. The settings will persist for the next write
202: * operation (write, decrement, increment, clear). Any reads that are done before the write, will
203: * use the modified settings. If `$settings` is empty, the settings will be reset to the
204: * original configuration.
205: *
206: * Can be called with 2 or 3 parameters. To set multiple values at once.
207: *
208: * `Cache::set(array('duration' => '+30 minutes'), 'my_config');`
209: *
210: * Or to set one value.
211: *
212: * `Cache::set('duration', '+30 minutes', 'my_config');`
213: *
214: * To reset a config back to the originally configured values.
215: *
216: * `Cache::set(null, 'my_config');`
217: *
218: * @param mixed $settings Optional string for simple name-value pair or array
219: * @param string $value Optional for a simple name-value pair
220: * @param string $config The configuration name you are changing. Defaults to 'default'
221: * @return array Array of settings.
222: */
223: public static function set($settings = array(), $value = null, $config = 'default') {
224: if (is_array($settings) && $value !== null) {
225: $config = $value;
226: }
227: if (!isset(self::$_config[$config]) || !isset(self::$_engines[$config])) {
228: return false;
229: }
230: if (!empty($settings)) {
231: self::$_reset = true;
232: }
233:
234: if (self::$_reset === true) {
235: if (empty($settings)) {
236: self::$_reset = false;
237: $settings = self::$_config[$config];
238: } else {
239: if (is_string($settings) && $value !== null) {
240: $settings = array($settings => $value);
241: }
242: $settings = array_merge(self::$_config[$config], $settings);
243: if (isset($settings['duration']) && !is_numeric($settings['duration'])) {
244: $settings['duration'] = strtotime($settings['duration']) - time();
245: }
246: }
247: self::$_engines[$config]->settings = $settings;
248: }
249: return self::settings($config);
250: }
251:
252: /**
253: * Garbage collection
254: *
255: * Permanently remove all expired and deleted data
256: *
257: * @param string $config The config name you wish to have garbage collected. Defaults to 'default'
258: * @return void
259: */
260: public static function gc($config = 'default') {
261: self::$_engines[$config]->gc();
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_integer($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_integer($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: * Check if Cache has initialized a working config for the given name.
460: *
461: * @param string $config name of the configuration to use. Defaults to 'default'
462: * @return boolean Whether or not the config name has been initialized.
463: */
464: public static function isInitialized($config = 'default') {
465: if (Configure::read('Cache.disable')) {
466: return false;
467: }
468: return isset(self::$_engines[$config]);
469: }
470:
471: /**
472: * Return the settings for the named cache engine.
473: *
474: * @param string $name Name of the configuration to get settings for. Defaults to 'default'
475: * @return array list of settings for this engine
476: * @see Cache::config()
477: */
478: public static function settings($name = 'default') {
479: if (!empty(self::$_engines[$name])) {
480: return self::$_engines[$name]->settings();
481: }
482: return array();
483: }
484: }
485:
486: /**
487: * Storage engine for CakePHP caching
488: *
489: * @package Cake.Cache
490: */
491: abstract class CacheEngine {
492:
493: /**
494: * Settings of current engine instance
495: *
496: * @var array
497: */
498: public $settings = array();
499:
500: /**
501: * Initialize the cache engine
502: *
503: * Called automatically by the cache frontend
504: *
505: * @param array $settings Associative array of parameters for the engine
506: * @return boolean True if the engine has been successfully initialized, false if not
507: */
508: public function init($settings = array()) {
509: $this->settings = array_merge(
510: array('prefix' => 'cake_', 'duration' => 3600, 'probability' => 100),
511: $this->settings,
512: $settings
513: );
514: if (!is_numeric($this->settings['duration'])) {
515: $this->settings['duration'] = strtotime($this->settings['duration']) - time();
516: }
517: return true;
518: }
519:
520: /**
521: * Garbage collection
522: *
523: * Permanently remove all expired and deleted data
524: * @return void
525: */
526: public function gc() { }
527:
528: /**
529: * Write value for a key into cache
530: *
531: * @param string $key Identifier for the data
532: * @param mixed $value Data to be cached
533: * @param mixed $duration How long to cache for.
534: * @return boolean True if the data was successfully cached, false on failure
535: */
536: abstract public function write($key, $value, $duration);
537:
538: /**
539: * Read a key from the cache
540: *
541: * @param string $key Identifier for the data
542: * @return mixed The cached data, or false if the data doesn't exist, has expired, or if there was an error fetching it
543: */
544: abstract public function read($key);
545:
546: /**
547: * Increment a number under the key and return incremented value
548: *
549: * @param string $key Identifier for the data
550: * @param integer $offset How much to add
551: * @return New incremented value, false otherwise
552: */
553: abstract public function increment($key, $offset = 1);
554:
555: /**
556: * Decrement a number under the key and return decremented value
557: *
558: * @param string $key Identifier for the data
559: * @param integer $offset How much to subtract
560: * @return New incremented value, false otherwise
561: */
562: abstract public function decrement($key, $offset = 1);
563:
564: /**
565: * Delete a key from the cache
566: *
567: * @param string $key Identifier for the data
568: * @return boolean True if the value was successfully deleted, false if it didn't exist or couldn't be removed
569: */
570: abstract public function delete($key);
571:
572: /**
573: * Delete all keys from the cache
574: *
575: * @param boolean $check if true will check expiration, otherwise delete all
576: * @return boolean True if the cache was successfully cleared, false otherwise
577: */
578: abstract public function clear($check);
579:
580: /**
581: * Cache Engine settings
582: *
583: * @return array settings
584: */
585: public function settings() {
586: return $this->settings;
587: }
588:
589: /**
590: * Generates a safe key for use with cache engine storage engines.
591: *
592: * @param string $key the key passed over
593: * @return mixed string $key or false
594: */
595: public function key($key) {
596: if (empty($key)) {
597: return false;
598: }
599: $key = Inflector::underscore(str_replace(array(DS, '/', '.'), '_', strval($key)));
600: return $key;
601: }
602: }
603: