Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

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