PageRenderTime 42ms CodeModel.GetById 9ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Cake/Cache/Cache.php

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