Cache.php 15 KB

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