Cache.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  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-2010, 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-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
  15. * @link http://cakephp.org CakePHP(tm) Project
  16. * @package cake.libs
  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.libs
  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 4 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. *
  88. * @see app/config/core.php for configuration settings
  89. * @param string $name Name of the configuration
  90. * @param array $settings Optional associative array of settings passed to the engine
  91. * @return array(engine, settings) on success, false on failure
  92. * @throws CacheException
  93. */
  94. public static function config($name = null, $settings = array()) {
  95. if (is_array($name)) {
  96. $settings = $name;
  97. }
  98. $current = array();
  99. if (isset(self::$_config[$name])) {
  100. $current = self::$_config[$name];
  101. }
  102. if (!empty($settings)) {
  103. self::$_config[$name] = array_merge($current, $settings);
  104. }
  105. if (empty(self::$_config[$name]['engine'])) {
  106. return false;
  107. }
  108. $engine = self::$_config[$name]['engine'];
  109. if (!isset(self::$_engines[$name])) {
  110. self::_buildEngine($name);
  111. $settings = self::$_config[$name] = self::settings($name);
  112. } elseif ($settings = self::set(self::$_config[$name], null, $name)) {
  113. self::$_config[$name] = $settings;
  114. }
  115. return compact('engine', 'settings');
  116. }
  117. /**
  118. * Finds and builds the instance of the required engine class.
  119. *
  120. * @param string $name Name of the config array that needs an engine instance built
  121. * @return void
  122. */
  123. protected static function _buildEngine($name) {
  124. $config = self::$_config[$name];
  125. list($plugin, $class) = pluginSplit($config['engine'], true);
  126. $cacheClass = $class . 'Engine';
  127. App::uses($cacheClass, $plugin . 'Cache/Engine');
  128. if (!class_exists($cacheClass)) {
  129. return false;
  130. }
  131. $cacheClass = $class . 'Engine';
  132. if (!is_subclass_of($cacheClass, 'CacheEngine')) {
  133. throw new CacheException(__('Cache engines must use CacheEngine as a base class.'));
  134. }
  135. self::$_engines[$name] = new $cacheClass();
  136. if (self::$_engines[$name]->init($config)) {
  137. if (time() % self::$_engines[$name]->settings['probability'] === 0) {
  138. self::$_engines[$name]->gc();
  139. }
  140. return true;
  141. }
  142. return false;
  143. }
  144. /**
  145. * Returns an array containing the currently configured Cache settings.
  146. *
  147. * @return array Array of configured Cache config names.
  148. */
  149. public static function configured() {
  150. return array_keys(self::$_config);
  151. }
  152. /**
  153. * Drops a cache engine. Deletes the cache configuration information
  154. * If the deleted configuration is the last configuration using an certain engine,
  155. * the Engine instance is also unset.
  156. *
  157. * @param string $name A currently configured cache config you wish to remove.
  158. * @return boolen success of the removal, returns false when the config does not exist.
  159. */
  160. public static function drop($name) {
  161. if (!isset(self::$_config[$name])) {
  162. return false;
  163. }
  164. unset(self::$_config[$name], self::$_engines[$name]);
  165. return true;
  166. }
  167. /**
  168. * Temporarily change the settings on a cache config. The settings will persist for the next write
  169. * operation (write, decrement, increment, clear). Any reads that are done before the write, will
  170. * use the modified settings. If `$settings` is empty, the settings will be reset to the
  171. * original configuration.
  172. *
  173. * Can be called with 2 or 3 parameters. To set multiple values at once.
  174. *
  175. * `Cache::set(array('duration' => '+30 minutes'), 'my_config');`
  176. *
  177. * Or to set one value.
  178. *
  179. * `Cache::set('duration', '+30 minutes', 'my_config');`
  180. *
  181. * To reset a config back to the originally configured values.
  182. *
  183. * `Cache::set(null, 'my_config');`
  184. *
  185. * @param mixed $settings Optional string for simple name-value pair or array
  186. * @param string $value Optional for a simple name-value pair
  187. * @param string $config The configuration name you are changing. Defaults to 'default'
  188. * @return array Array of settings.
  189. */
  190. public static function set($settings = array(), $value = null, $config = 'default') {
  191. if (is_array($settings) && $value !== null) {
  192. $config = $value;
  193. }
  194. if (!isset(self::$_config[$config]) || !isset(self::$_engines[$config])) {
  195. return false;
  196. }
  197. if (!empty($settings)) {
  198. self::$_reset = true;
  199. }
  200. if (self::$_reset === true) {
  201. if (empty($settings)) {
  202. self::$_reset = false;
  203. $settings = self::$_config[$config];
  204. } else {
  205. if (is_string($settings) && $value !== null) {
  206. $settings = array($settings => $value);
  207. }
  208. $settings = array_merge(self::$_config[$config], $settings);
  209. if (isset($settings['duration']) && !is_numeric($settings['duration'])) {
  210. $settings['duration'] = strtotime($settings['duration']) - time();
  211. }
  212. }
  213. self::$_engines[$config]->settings = $settings;
  214. }
  215. return self::settings($config);
  216. }
  217. /**
  218. * Garbage collection
  219. *
  220. * Permanently remove all expired and deleted data
  221. *
  222. * @param string $config The config name you wish to have garbage collected. Defaults to 'default'
  223. * @return void
  224. */
  225. public static function gc($config = 'default') {
  226. self::$_engines[$config]->gc();
  227. }
  228. /**
  229. * Write data for key into cache. Will automatically use the currently
  230. * active cache configuration. To set the currently active configuration use
  231. * Cache::config()
  232. *
  233. * ### Usage:
  234. *
  235. * Writing to the active cache config:
  236. *
  237. * `Cache::write('cached_data', $data);`
  238. *
  239. * Writing to a specific cache config:
  240. *
  241. * `Cache::write('cached_data', $data, 'long_term');`
  242. *
  243. * @param string $key Identifier for the data
  244. * @param mixed $value Data to be cached - anything except a resource
  245. * @param string $config Optional string configuration name to write to. Defaults to 'default'
  246. * @return boolean True if the data was successfully cached, false on failure
  247. */
  248. public static function write($key, $value, $config = 'default') {
  249. $settings = self::settings($config);
  250. if (empty($settings)) {
  251. return null;
  252. }
  253. if (!self::isInitialized($config)) {
  254. return false;
  255. }
  256. $key = self::$_engines[$config]->key($key);
  257. if (!$key || is_resource($value)) {
  258. return false;
  259. }
  260. $success = self::$_engines[$config]->write($settings['prefix'] . $key, $value, $settings['duration']);
  261. self::set(null, $config);
  262. if ($success === false && $value !== '') {
  263. trigger_error(
  264. __("%s cache was unable to write '%s' to cache", $config, $key),
  265. E_USER_WARNING
  266. );
  267. }
  268. return $success;
  269. }
  270. /**
  271. * Read a key from the cache. Will automatically use the currently
  272. * active cache configuration. To set the currently active configuration use
  273. * Cache::config()
  274. *
  275. * ### Usage:
  276. *
  277. * Reading from the active cache configuration.
  278. *
  279. * `Cache::read('my_data');`
  280. *
  281. * Reading from a specific cache configuration.
  282. *
  283. * `Cache::read('my_data', 'long_term');`
  284. *
  285. * @param string $key Identifier for the data
  286. * @param string $config optional name of the configuration to use. Defaults to 'default'
  287. * @return mixed The cached data, or false if the data doesn't exist, has expired, or if there was an error fetching it
  288. */
  289. public static function read($key, $config = 'default') {
  290. $settings = self::settings($config);
  291. if (empty($settings)) {
  292. return null;
  293. }
  294. if (!self::isInitialized($config)) {
  295. return false;
  296. }
  297. $key = self::$_engines[$config]->key($key);
  298. if (!$key) {
  299. return false;
  300. }
  301. return self::$_engines[$config]->read($settings['prefix'] . $key);
  302. }
  303. /**
  304. * Increment a number under the key and return incremented value.
  305. *
  306. * @param string $key Identifier for the data
  307. * @param integer $offset How much to add
  308. * @param string $config Optional string configuration name. Defaults to 'default'
  309. * @return mixed new value, or false if the data doesn't exist, is not integer,
  310. * or if there was an error fetching it.
  311. */
  312. public static function increment($key, $offset = 1, $config = 'default') {
  313. $settings = self::settings($config);
  314. if (empty($settings)) {
  315. return null;
  316. }
  317. if (!self::isInitialized($config)) {
  318. return false;
  319. }
  320. $key = self::$_engines[$config]->key($key);
  321. if (!$key || !is_integer($offset) || $offset < 0) {
  322. return false;
  323. }
  324. $success = self::$_engines[$config]->increment($settings['prefix'] . $key, $offset);
  325. self::set(null, $config);
  326. return $success;
  327. }
  328. /**
  329. * Decrement a number under the key and return decremented value.
  330. *
  331. * @param string $key Identifier for the data
  332. * @param integer $offset How much to substract
  333. * @param string $config Optional string configuration name. Defaults to 'default'
  334. * @return mixed new value, or false if the data doesn't exist, is not integer,
  335. * or if there was an error fetching it
  336. */
  337. public static function decrement($key, $offset = 1, $config = 'default') {
  338. $settings = self::settings($config);
  339. if (empty($settings)) {
  340. return null;
  341. }
  342. if (!self::isInitialized($config)) {
  343. return false;
  344. }
  345. $key = self::$_engines[$config]->key($key);
  346. if (!$key || !is_integer($offset) || $offset < 0) {
  347. return false;
  348. }
  349. $success = self::$_engines[$config]->decrement($settings['prefix'] . $key, $offset);
  350. self::set(null, $config);
  351. return $success;
  352. }
  353. /**
  354. * Delete a key from the cache.
  355. *
  356. * ### Usage:
  357. *
  358. * Deleting from the active cache configuration.
  359. *
  360. * `Cache::delete('my_data');`
  361. *
  362. * Deleting from a specific cache configuration.
  363. *
  364. * `Cache::delete('my_data', 'long_term');`
  365. *
  366. * @param string $key Identifier for the data
  367. * @param string $config name of the configuration to use. Defaults to 'default'
  368. * @return boolean True if the value was succesfully deleted, false if it didn't exist or couldn't be removed
  369. */
  370. public static function delete($key, $config = 'default') {
  371. $settings = self::settings($config);
  372. if (empty($settings)) {
  373. return null;
  374. }
  375. if (!self::isInitialized($config)) {
  376. return false;
  377. }
  378. $key = self::$_engines[$config]->key($key);
  379. if (!$key) {
  380. return false;
  381. }
  382. $success = self::$_engines[$config]->delete($settings['prefix'] . $key);
  383. self::set(null, $config);
  384. return $success;
  385. }
  386. /**
  387. * Delete all keys from the cache.
  388. *
  389. * @param boolean $check if true will check expiration, otherwise delete all
  390. * @param string $config name of the configuration to use. Defaults to 'default'
  391. * @return boolean True if the cache was succesfully cleared, false otherwise
  392. */
  393. public static function clear($check = false, $config = 'default') {
  394. if (!self::isInitialized($config)) {
  395. return false;
  396. }
  397. $success = self::$_engines[$config]->clear($check);
  398. self::set(null, $config);
  399. return $success;
  400. }
  401. /**
  402. * Check if Cache has initialized a working config for the given name.
  403. *
  404. * @param string $engine Name of the engine, Defaults to default
  405. * @param string $config Name of the configuration setting
  406. * @return bool Whether or not the config name has been initialized.
  407. */
  408. public static function isInitialized($name = 'default') {
  409. if (Configure::read('Cache.disable')) {
  410. return false;
  411. }
  412. return isset(self::$_engines[$name]);
  413. }
  414. /**
  415. * Return the settings for the named cache engine.
  416. *
  417. * @param string $engine Name of the configuration to get settings for. Defaults to 'default'
  418. * @return array list of settings for this engine
  419. * @see Cache::config()
  420. * @access public
  421. * @static
  422. */
  423. public static function settings($name = 'default') {
  424. if (!empty(self::$_engines[$name])) {
  425. return self::$_engines[$name]->settings();
  426. }
  427. return array();
  428. }
  429. }
  430. /**
  431. * Storage engine for CakePHP caching
  432. *
  433. * @package cake.libs
  434. */
  435. abstract class CacheEngine {
  436. /**
  437. * Settings of current engine instance
  438. *
  439. * @var int
  440. * @access public
  441. */
  442. public $settings = array();
  443. /**
  444. * Initialize the cache engine
  445. *
  446. * Called automatically by the cache frontend
  447. *
  448. * @param array $params Associative array of parameters for the engine
  449. * @return boolean True if the engine has been succesfully initialized, false if not
  450. */
  451. public function init($settings = array()) {
  452. $this->settings = array_merge(
  453. array('prefix' => 'cake_', 'duration'=> 3600, 'probability'=> 100),
  454. $this->settings,
  455. $settings
  456. );
  457. if (!is_numeric($this->settings['duration'])) {
  458. $this->settings['duration'] = strtotime($this->settings['duration']) - time();
  459. }
  460. return true;
  461. }
  462. /**
  463. * Garbage collection
  464. *
  465. * Permanently remove all expired and deleted data
  466. * @return void
  467. */
  468. public function gc() { }
  469. /**
  470. * Write value for a key into cache
  471. *
  472. * @param string $key Identifier for the data
  473. * @param mixed $value Data to be cached
  474. * @param mixed $duration How long to cache for.
  475. * @return boolean True if the data was succesfully cached, false on failure
  476. */
  477. abstract public function write($key, $value, $duration);
  478. /**
  479. * Read a key from the cache
  480. *
  481. * @param string $key Identifier for the data
  482. * @return mixed The cached data, or false if the data doesn't exist, has expired, or if there was an error fetching it
  483. */
  484. abstract public function read($key);
  485. /**
  486. * Increment a number under the key and return incremented value
  487. *
  488. * @param string $key Identifier for the data
  489. * @param integer $offset How much to add
  490. * @return New incremented value, false otherwise
  491. */
  492. abstract public function increment($key, $offset = 1);
  493. /**
  494. * Decrement a number under the key and return decremented value
  495. *
  496. * @param string $key Identifier for the data
  497. * @param integer $value How much to substract
  498. * @return New incremented value, false otherwise
  499. */
  500. abstract public function decrement($key, $offset = 1);
  501. /**
  502. * Delete a key from the cache
  503. *
  504. * @param string $key Identifier for the data
  505. * @return boolean True if the value was succesfully deleted, false if it didn't exist or couldn't be removed
  506. */
  507. abstract public function delete($key);
  508. /**
  509. * Delete all keys from the cache
  510. *
  511. * @param boolean $check if true will check expiration, otherwise delete all
  512. * @return boolean True if the cache was succesfully cleared, false otherwise
  513. */
  514. abstract public function clear($check);
  515. /**
  516. * Cache Engine settings
  517. *
  518. * @return array settings
  519. */
  520. public function settings() {
  521. return $this->settings;
  522. }
  523. /**
  524. * Generates a safe key for use with cache engine storage engines.
  525. *
  526. * @param string $key the key passed over
  527. * @return mixed string $key or false
  528. */
  529. public function key($key) {
  530. if (empty($key)) {
  531. return false;
  532. }
  533. $key = Inflector::underscore(str_replace(array(DS, '/', '.'), '_', strval($key)));
  534. return $key;
  535. }
  536. }