1: <?php
2: /**
3: * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
4: * Copyright (c) Cake Software Foundation, Inc. (https://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. (https://cakefoundation.org)
11: * @link https://cakephp.org CakePHP(tm) Project
12: * @since 1.2.0
13: * @license https://opensource.org/licenses/mit-license.php MIT License
14: */
15: namespace Cake\Cache;
16:
17: use Cake\Cache\Engine\NullEngine;
18: use Cake\Core\ObjectRegistry;
19: use Cake\Core\StaticConfigTrait;
20: use InvalidArgumentException;
21: use RuntimeException;
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: * ### Configuring Cache engines
30: *
31: * You can configure Cache engines in your application's `Config/cache.php` file.
32: * A sample configuration would be:
33: *
34: * ```
35: * Cache::config('shared', [
36: * 'className' => 'Cake\Cache\Engine\ApcuEngine',
37: * 'prefix' => 'my_app_'
38: * ]);
39: * ```
40: *
41: * This would configure an APCu cache engine to the 'shared' alias. You could then read and write
42: * to that cache alias by using it for the `$config` parameter in the various Cache methods.
43: *
44: * In general all Cache operations are supported by all cache engines.
45: * However, Cache::increment() and Cache::decrement() are not supported by File caching.
46: *
47: * There are 7 built-in caching engines:
48: *
49: * - `ApcuEngine` - Uses the APCu object cache, one of the fastest caching engines.
50: * - `ArrayEngine` - Uses only memory to store all data, not actually a persistent engine.
51: * Can be useful in test or CLI environment.
52: * - `FileEngine` - Uses simple files to store content. Poor performance, but good for
53: * storing large objects, or things that are not IO sensitive. Well suited to development
54: * as it is an easy cache to inspect and manually flush.
55: * - `MemcacheEngine` - Uses the PECL::Memcache extension and Memcached for storage.
56: * Fast reads/writes, and benefits from memcache being distributed.
57: * - `RedisEngine` - Uses redis and php-redis extension to store cache data.
58: * - `WincacheEngine` - Uses Windows Cache Extension for PHP. Supports wincache 1.1.0 and higher.
59: * This engine is recommended to people deploying on windows with IIS.
60: * - `XcacheEngine` - Uses the Xcache extension, an alternative to APCu.
61: *
62: * See Cache engine documentation for expected configuration keys.
63: *
64: * @see config/app.php for configuration settings
65: */
66: class Cache
67: {
68: use StaticConfigTrait;
69:
70: /**
71: * An array mapping url schemes to fully qualified caching engine
72: * class names.
73: *
74: * @var array
75: */
76: protected static $_dsnClassMap = [
77: 'array' => 'Cake\Cache\Engine\ArrayEngine',
78: 'apc' => 'Cake\Cache\Engine\ApcuEngine', // @deprecated Since 3.6. Use apcu instead.
79: 'apcu' => 'Cake\Cache\Engine\ApcuEngine',
80: 'file' => 'Cake\Cache\Engine\FileEngine',
81: 'memcached' => 'Cake\Cache\Engine\MemcachedEngine',
82: 'null' => 'Cake\Cache\Engine\NullEngine',
83: 'redis' => 'Cake\Cache\Engine\RedisEngine',
84: 'wincache' => 'Cake\Cache\Engine\WincacheEngine',
85: 'xcache' => 'Cake\Cache\Engine\XcacheEngine',
86: ];
87:
88: /**
89: * Flag for tracking whether or not caching is enabled.
90: *
91: * @var bool
92: */
93: protected static $_enabled = true;
94:
95: /**
96: * Group to Config mapping
97: *
98: * @var array
99: */
100: protected static $_groups = [];
101:
102: /**
103: * Cache Registry used for creating and using cache adapters.
104: *
105: * @var \Cake\Core\ObjectRegistry
106: */
107: protected static $_registry;
108:
109: /**
110: * Returns the Cache Registry instance used for creating and using cache adapters.
111: *
112: * @return \Cake\Core\ObjectRegistry
113: */
114: public static function getRegistry()
115: {
116: if (!static::$_registry) {
117: static::$_registry = new CacheRegistry();
118: }
119:
120: return static::$_registry;
121: }
122:
123: /**
124: * Sets the Cache Registry instance used for creating and using cache adapters.
125: *
126: * Also allows for injecting of a new registry instance.
127: *
128: * @param \Cake\Core\ObjectRegistry $registry Injectable registry object.
129: * @return void
130: */
131: public static function setRegistry(ObjectRegistry $registry)
132: {
133: static::$_registry = $registry;
134: }
135:
136: /**
137: * Returns the Cache Registry instance used for creating and using cache adapters.
138: * Also allows for injecting of a new registry instance.
139: *
140: * @param \Cake\Core\ObjectRegistry|null $registry Injectable registry object.
141: * @return \Cake\Core\ObjectRegistry
142: * @deprecated Deprecated since 3.5. Use getRegistry() and setRegistry() instead.
143: */
144: public static function registry(ObjectRegistry $registry = null)
145: {
146: deprecationWarning('Use Cache::getRegistry() and Cache::setRegistry() instead.');
147: if ($registry) {
148: static::setRegistry($registry);
149: }
150:
151: return static::getRegistry();
152: }
153:
154: /**
155: * Finds and builds the instance of the required engine class.
156: *
157: * @param string $name Name of the config array that needs an engine instance built
158: * @return void
159: * @throws \InvalidArgumentException When a cache engine cannot be created.
160: */
161: protected static function _buildEngine($name)
162: {
163: $registry = static::getRegistry();
164:
165: if (empty(static::$_config[$name]['className'])) {
166: throw new InvalidArgumentException(
167: sprintf('The "%s" cache configuration does not exist.', $name)
168: );
169: }
170:
171: $config = static::$_config[$name];
172:
173: try {
174: $registry->load($name, $config);
175: } catch (RuntimeException $e) {
176: if (!array_key_exists('fallback', $config)) {
177: $registry->set($name, new NullEngine());
178: trigger_error($e->getMessage(), E_USER_WARNING);
179:
180: return;
181: }
182:
183: if ($config['fallback'] === false) {
184: throw $e;
185: }
186:
187: if ($config['fallback'] === $name) {
188: throw new InvalidArgumentException(sprintf('"%s" cache configuration cannot fallback to itself.', $name), null, $e);
189: }
190:
191: $fallbackEngine = clone static::engine($config['fallback']);
192: $newConfig = $config + ['groups' => [], 'prefix' => null];
193: $fallbackEngine->setConfig('groups', $newConfig['groups'], false);
194: if ($newConfig['prefix']) {
195: $fallbackEngine->setConfig('prefix', $newConfig['prefix'], false);
196: }
197: $registry->set($name, $fallbackEngine);
198: }
199:
200: if ($config['className'] instanceof CacheEngine) {
201: $config = $config['className']->getConfig();
202: }
203:
204: if (!empty($config['groups'])) {
205: foreach ($config['groups'] as $group) {
206: static::$_groups[$group][] = $name;
207: static::$_groups[$group] = array_unique(static::$_groups[$group]);
208: sort(static::$_groups[$group]);
209: }
210: }
211: }
212:
213: /**
214: * Fetch the engine attached to a specific configuration name.
215: *
216: * If the cache engine & configuration are missing an error will be
217: * triggered.
218: *
219: * @param string $config The configuration name you want an engine for.
220: * @return \Cake\Cache\CacheEngine When caching is disabled a null engine will be returned.
221: * @deprecated 3.7.0 Use Cache::pool() instead. In 4.0 all cache engines will implement the
222: * PSR16 interface and this method does not return objects implementing that interface.
223: */
224: public static function engine($config)
225: {
226: if (!static::$_enabled) {
227: return new NullEngine();
228: }
229:
230: $registry = static::getRegistry();
231:
232: if (isset($registry->{$config})) {
233: return $registry->{$config};
234: }
235:
236: static::_buildEngine($config);
237:
238: return $registry->{$config};
239: }
240:
241: /**
242: * Get a SimpleCacheEngine object for the named cache pool.
243: *
244: * @param string $config The name of the configured cache backend.
245: * @return \Cake\Cache\SimpleCacheEngine
246: */
247: public static function pool($config)
248: {
249: return new SimpleCacheEngine(static::engine($config));
250: }
251:
252: /**
253: * Garbage collection
254: *
255: * Permanently remove all expired and deleted data
256: *
257: * @param string $config [optional] The config name you wish to have garbage collected. Defaults to 'default'
258: * @param int|null $expires [optional] An expires timestamp. Defaults to NULL
259: * @return void
260: * @deprecated 3.7.0 Will be removed in 4.0
261: */
262: public static function gc($config = 'default', $expires = null)
263: {
264: $engine = static::engine($config);
265: $engine->gc($expires);
266: }
267:
268: /**
269: * Write data for key into cache.
270: *
271: * ### Usage:
272: *
273: * Writing to the active cache config:
274: *
275: * ```
276: * Cache::write('cached_data', $data);
277: * ```
278: *
279: * Writing to a specific cache config:
280: *
281: * ```
282: * Cache::write('cached_data', $data, 'long_term');
283: * ```
284: *
285: * @param string $key Identifier for the data
286: * @param mixed $value Data to be cached - anything except a resource
287: * @param string $config Optional string configuration name to write to. Defaults to 'default'
288: * @return bool True if the data was successfully cached, false on failure
289: */
290: public static function write($key, $value, $config = 'default')
291: {
292: if (is_resource($value)) {
293: return false;
294: }
295:
296: $backend = static::pool($config);
297: $success = $backend->set($key, $value);
298: if ($success === false && $value !== '') {
299: trigger_error(
300: sprintf(
301: "%s cache was unable to write '%s' to %s cache",
302: $config,
303: $key,
304: get_class($backend)
305: ),
306: E_USER_WARNING
307: );
308: }
309:
310: return $success;
311: }
312:
313: /**
314: * Write data for many keys into cache.
315: *
316: * ### Usage:
317: *
318: * Writing to the active cache config:
319: *
320: * ```
321: * Cache::writeMany(['cached_data_1' => 'data 1', 'cached_data_2' => 'data 2']);
322: * ```
323: *
324: * Writing to a specific cache config:
325: *
326: * ```
327: * Cache::writeMany(['cached_data_1' => 'data 1', 'cached_data_2' => 'data 2'], 'long_term');
328: * ```
329: *
330: * @param array $data An array of data to be stored in the cache
331: * @param string $config Optional string configuration name to write to. Defaults to 'default'
332: * @return array of bools for each key provided, indicating true for success or false for fail
333: * @throws \RuntimeException
334: */
335: public static function writeMany($data, $config = 'default')
336: {
337: $engine = static::engine($config);
338:
339: $return = $engine->writeMany($data);
340: foreach ($return as $key => $success) {
341: if ($success === false && $data[$key] !== '') {
342: throw new RuntimeException(sprintf(
343: '%s cache was unable to write \'%s\' to %s cache',
344: $config,
345: $key,
346: get_class($engine)
347: ));
348: }
349: }
350:
351: return $return;
352: }
353:
354: /**
355: * Read a key from the cache.
356: *
357: * ### Usage:
358: *
359: * Reading from the active cache configuration.
360: *
361: * ```
362: * Cache::read('my_data');
363: * ```
364: *
365: * Reading from a specific cache configuration.
366: *
367: * ```
368: * Cache::read('my_data', 'long_term');
369: * ```
370: *
371: * @param string $key Identifier for the data
372: * @param string $config optional name of the configuration to use. Defaults to 'default'
373: * @return mixed The cached data, or false if the data doesn't exist, has expired, or if there was an error fetching it
374: */
375: public static function read($key, $config = 'default')
376: {
377: // TODO In 4.x this needs to change to use pool()
378: $engine = static::engine($config);
379:
380: return $engine->read($key);
381: }
382:
383: /**
384: * Read multiple keys from the cache.
385: *
386: * ### Usage:
387: *
388: * Reading multiple keys from the active cache configuration.
389: *
390: * ```
391: * Cache::readMany(['my_data_1', 'my_data_2]);
392: * ```
393: *
394: * Reading from a specific cache configuration.
395: *
396: * ```
397: * Cache::readMany(['my_data_1', 'my_data_2], 'long_term');
398: * ```
399: *
400: * @param array $keys an array of keys to fetch from the cache
401: * @param string $config optional name of the configuration to use. Defaults to 'default'
402: * @return array An array containing, for each of the given $keys, the cached data or false if cached data could not be
403: * retrieved.
404: */
405: public static function readMany($keys, $config = 'default')
406: {
407: // In 4.x this needs to change to use pool()
408: $engine = static::engine($config);
409:
410: return $engine->readMany($keys);
411: }
412:
413: /**
414: * Increment a number under the key and return incremented value.
415: *
416: * @param string $key Identifier for the data
417: * @param int $offset How much to add
418: * @param string $config Optional string configuration name. Defaults to 'default'
419: * @return int|false New value, or false if the data doesn't exist, is not integer,
420: * or if there was an error fetching it.
421: */
422: public static function increment($key, $offset = 1, $config = 'default')
423: {
424: $engine = static::pool($config);
425: if (!is_int($offset) || $offset < 0) {
426: return false;
427: }
428:
429: return $engine->increment($key, $offset);
430: }
431:
432: /**
433: * Decrement a number under the key and return decremented value.
434: *
435: * @param string $key Identifier for the data
436: * @param int $offset How much to subtract
437: * @param string $config Optional string configuration name. Defaults to 'default'
438: * @return int|false New value, or false if the data doesn't exist, is not integer,
439: * or if there was an error fetching it
440: */
441: public static function decrement($key, $offset = 1, $config = 'default')
442: {
443: $engine = static::pool($config);
444: if (!is_int($offset) || $offset < 0) {
445: return false;
446: }
447:
448: return $engine->decrement($key, $offset);
449: }
450:
451: /**
452: * Delete a key from the cache.
453: *
454: * ### Usage:
455: *
456: * Deleting from the active cache configuration.
457: *
458: * ```
459: * Cache::delete('my_data');
460: * ```
461: *
462: * Deleting from a specific cache configuration.
463: *
464: * ```
465: * Cache::delete('my_data', 'long_term');
466: * ```
467: *
468: * @param string $key Identifier for the data
469: * @param string $config name of the configuration to use. Defaults to 'default'
470: * @return bool True if the value was successfully deleted, false if it didn't exist or couldn't be removed
471: */
472: public static function delete($key, $config = 'default')
473: {
474: $backend = static::pool($config);
475:
476: return $backend->delete($key);
477: }
478:
479: /**
480: * Delete many keys from the cache.
481: *
482: * ### Usage:
483: *
484: * Deleting multiple keys from the active cache configuration.
485: *
486: * ```
487: * Cache::deleteMany(['my_data_1', 'my_data_2']);
488: * ```
489: *
490: * Deleting from a specific cache configuration.
491: *
492: * ```
493: * Cache::deleteMany(['my_data_1', 'my_data_2], 'long_term');
494: * ```
495: *
496: * @param array $keys Array of cache keys to be deleted
497: * @param string $config name of the configuration to use. Defaults to 'default'
498: * @return array of boolean values that are true if the value was successfully deleted,
499: * false if it didn't exist or couldn't be removed.
500: */
501: public static function deleteMany($keys, $config = 'default')
502: {
503: $backend = static::pool($config);
504:
505: $return = [];
506: foreach ($keys as $key) {
507: $return[$key] = $backend->delete($key);
508: }
509:
510: return $return;
511: }
512:
513: /**
514: * Delete all keys from the cache.
515: *
516: * @param bool $check if true will check expiration, otherwise delete all. This parameter
517: * will become a no-op value in 4.0 as it is deprecated.
518: * @param string $config name of the configuration to use. Defaults to 'default'
519: * @return bool True if the cache was successfully cleared, false otherwise
520: */
521: public static function clear($check = false, $config = 'default')
522: {
523: $engine = static::engine($config);
524:
525: return $engine->clear($check);
526: }
527:
528: /**
529: * Delete all keys from the cache from all configurations.
530: *
531: * @param bool $check if true will check expiration, otherwise delete all. This parameter
532: * will become a no-op value in 4.0 as it is deprecated.
533: * @return array Status code. For each configuration, it reports the status of the operation
534: */
535: public static function clearAll($check = false)
536: {
537: $status = [];
538:
539: foreach (self::configured() as $config) {
540: $status[$config] = self::clear($check, $config);
541: }
542:
543: return $status;
544: }
545:
546: /**
547: * Delete all keys from the cache belonging to the same group.
548: *
549: * @param string $group name of the group to be cleared
550: * @param string $config name of the configuration to use. Defaults to 'default'
551: * @return bool True if the cache group was successfully cleared, false otherwise
552: */
553: public static function clearGroup($group, $config = 'default')
554: {
555: $engine = static::pool($config);
556:
557: return $engine->clearGroup($group);
558: }
559:
560: /**
561: * Retrieve group names to config mapping.
562: *
563: * ```
564: * Cache::config('daily', ['duration' => '1 day', 'groups' => ['posts']]);
565: * Cache::config('weekly', ['duration' => '1 week', 'groups' => ['posts', 'archive']]);
566: * $configs = Cache::groupConfigs('posts');
567: * ```
568: *
569: * $configs will equal to `['posts' => ['daily', 'weekly']]`
570: * Calling this method will load all the configured engines.
571: *
572: * @param string|null $group group name or null to retrieve all group mappings
573: * @return array map of group and all configuration that has the same group
574: * @throws \InvalidArgumentException
575: */
576: public static function groupConfigs($group = null)
577: {
578: foreach (array_keys(static::$_config) as $config) {
579: static::engine($config);
580: }
581: if ($group === null) {
582: return static::$_groups;
583: }
584:
585: if (isset(self::$_groups[$group])) {
586: return [$group => self::$_groups[$group]];
587: }
588:
589: throw new InvalidArgumentException(sprintf('Invalid cache group %s', $group));
590: }
591:
592: /**
593: * Re-enable caching.
594: *
595: * If caching has been disabled with Cache::disable() this method will reverse that effect.
596: *
597: * @return void
598: */
599: public static function enable()
600: {
601: static::$_enabled = true;
602: }
603:
604: /**
605: * Disable caching.
606: *
607: * When disabled all cache operations will return null.
608: *
609: * @return void
610: */
611: public static function disable()
612: {
613: static::$_enabled = false;
614: }
615:
616: /**
617: * Check whether or not caching is enabled.
618: *
619: * @return bool
620: */
621: public static function enabled()
622: {
623: return static::$_enabled;
624: }
625:
626: /**
627: * Provides the ability to easily do read-through caching.
628: *
629: * When called if the $key is not set in $config, the $callable function
630: * will be invoked. The results will then be stored into the cache config
631: * at key.
632: *
633: * Examples:
634: *
635: * Using a Closure to provide data, assume `$this` is a Table object:
636: *
637: * ```
638: * $results = Cache::remember('all_articles', function () {
639: * return $this->find('all');
640: * });
641: * ```
642: *
643: * @param string $key The cache key to read/store data at.
644: * @param callable $callable The callable that provides data in the case when
645: * the cache key is empty. Can be any callable type supported by your PHP.
646: * @param string $config The cache configuration to use for this operation.
647: * Defaults to default.
648: * @return mixed If the key is found: the cached data, false if the data
649: * missing/expired, or an error. If the key is not found: boolean of the
650: * success of the write
651: */
652: public static function remember($key, $callable, $config = 'default')
653: {
654: $existing = self::read($key, $config);
655: if ($existing !== false) {
656: return $existing;
657: }
658: $results = call_user_func($callable);
659: self::write($key, $results, $config);
660:
661: return $results;
662: }
663:
664: /**
665: * Write data for key into a cache engine if it doesn't exist already.
666: *
667: * ### Usage:
668: *
669: * Writing to the active cache config:
670: *
671: * ```
672: * Cache::add('cached_data', $data);
673: * ```
674: *
675: * Writing to a specific cache config:
676: *
677: * ```
678: * Cache::add('cached_data', $data, 'long_term');
679: * ```
680: *
681: * @param string $key Identifier for the data.
682: * @param mixed $value Data to be cached - anything except a resource.
683: * @param string $config Optional string configuration name to write to. Defaults to 'default'.
684: * @return bool True if the data was successfully cached, false on failure.
685: * Or if the key existed already.
686: */
687: public static function add($key, $value, $config = 'default')
688: {
689: $pool = static::pool($config);
690: if (is_resource($value)) {
691: return false;
692: }
693:
694: return $pool->add($key, $value);
695: }
696: }
697: