/framework/vendor/zend/Zend/Cache/Backend/TwoLevels.php

http://zoop.googlecode.com/ · PHP · 506 lines · 228 code · 31 blank · 247 comment · 35 complexity · 39ebf1a95035993da21b17bd3d5b6001 MD5 · raw file

  1. <?php
  2. /**
  3. * Zend Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the new BSD license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://framework.zend.com/license/new-bsd
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@zend.com so we can send you a copy immediately.
  14. *
  15. * @category Zend
  16. * @package Zend_Cache
  17. * @subpackage Zend_Cache_Backend
  18. * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
  19. * @license http://framework.zend.com/license/new-bsd New BSD License
  20. * @version $Id: TwoLevels.php 20096 2010-01-06 02:05:09Z bkarwin $
  21. */
  22. /**
  23. * @see Zend_Cache_Backend_ExtendedInterface
  24. */
  25. require_once 'Zend/Cache/Backend/ExtendedInterface.php';
  26. /**
  27. * @see Zend_Cache_Backend
  28. */
  29. require_once 'Zend/Cache/Backend.php';
  30. /**
  31. * @package Zend_Cache
  32. * @subpackage Zend_Cache_Backend
  33. * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
  34. * @license http://framework.zend.com/license/new-bsd New BSD License
  35. */
  36. class Zend_Cache_Backend_TwoLevels extends Zend_Cache_Backend implements Zend_Cache_Backend_ExtendedInterface
  37. {
  38. /**
  39. * Available options
  40. *
  41. * =====> (string) slow_backend :
  42. * - Slow backend name
  43. * - Must implement the Zend_Cache_Backend_ExtendedInterface
  44. * - Should provide a big storage
  45. *
  46. * =====> (string) fast_backend :
  47. * - Flow backend name
  48. * - Must implement the Zend_Cache_Backend_ExtendedInterface
  49. * - Must be much faster than slow_backend
  50. *
  51. * =====> (array) slow_backend_options :
  52. * - Slow backend options (see corresponding backend)
  53. *
  54. * =====> (array) fast_backend_options :
  55. * - Fast backend options (see corresponding backend)
  56. *
  57. * =====> (int) stats_update_factor :
  58. * - Disable / Tune the computation of the fast backend filling percentage
  59. * - When saving a record into cache :
  60. * 1 => systematic computation of the fast backend filling percentage
  61. * x (integer) > 1 => computation of the fast backend filling percentage randomly 1 times on x cache write
  62. *
  63. * =====> (boolean) slow_backend_custom_naming :
  64. * =====> (boolean) fast_backend_custom_naming :
  65. * =====> (boolean) slow_backend_autoload :
  66. * =====> (boolean) fast_backend_autoload :
  67. * - See Zend_Cache::factory() method
  68. *
  69. * =====> (boolean) auto_refresh_fast_cache
  70. * - If true, auto refresh the fast cache when a cache record is hit
  71. *
  72. * @var array available options
  73. */
  74. protected $_options = array(
  75. 'slow_backend' => 'File',
  76. 'fast_backend' => 'Apc',
  77. 'slow_backend_options' => array(),
  78. 'fast_backend_options' => array(),
  79. 'stats_update_factor' => 10,
  80. 'slow_backend_custom_naming' => false,
  81. 'fast_backend_custom_naming' => false,
  82. 'slow_backend_autoload' => false,
  83. 'fast_backend_autoload' => false,
  84. 'auto_refresh_fast_cache' => true
  85. );
  86. /**
  87. * Slow Backend
  88. *
  89. * @var Zend_Cache_Backend
  90. */
  91. protected $_slowBackend;
  92. /**
  93. * Fast Backend
  94. *
  95. * @var Zend_Cache_Backend
  96. */
  97. protected $_fastBackend;
  98. /**
  99. * Cache for the fast backend filling percentage
  100. *
  101. * @var int
  102. */
  103. protected $_fastBackendFillingPercentage = null;
  104. /**
  105. * Constructor
  106. *
  107. * @param array $options Associative array of options
  108. * @throws Zend_Cache_Exception
  109. * @return void
  110. */
  111. public function __construct(array $options = array())
  112. {
  113. parent::__construct($options);
  114. if ($this->_options['slow_backend'] === null) {
  115. Zend_Cache::throwException('slow_backend option has to set');
  116. }
  117. if ($this->_options['fast_backend'] === null) {
  118. Zend_Cache::throwException('fast_backend option has to set');
  119. }
  120. $this->_slowBackend = Zend_Cache::_makeBackend($this->_options['slow_backend'], $this->_options['slow_backend_options'], $this->_options['slow_backend_custom_naming'], $this->_options['slow_backend_autoload']);
  121. $this->_fastBackend = Zend_Cache::_makeBackend($this->_options['fast_backend'], $this->_options['fast_backend_options'], $this->_options['fast_backend_custom_naming'], $this->_options['fast_backend_autoload']);
  122. if (!in_array('Zend_Cache_Backend_ExtendedInterface', class_implements($this->_slowBackend))) {
  123. Zend_Cache::throwException('slow_backend must implement the Zend_Cache_Backend_ExtendedInterface interface');
  124. }
  125. if (!in_array('Zend_Cache_Backend_ExtendedInterface', class_implements($this->_fastBackend))) {
  126. Zend_Cache::throwException('fast_backend must implement the Zend_Cache_Backend_ExtendedInterface interface');
  127. }
  128. $this->_slowBackend->setDirectives($this->_directives);
  129. $this->_fastBackend->setDirectives($this->_directives);
  130. }
  131. /**
  132. * Test if a cache is available or not (for the given id)
  133. *
  134. * @param string $id cache id
  135. * @return mixed|false (a cache is not available) or "last modified" timestamp (int) of the available cache record
  136. */
  137. public function test($id)
  138. {
  139. $fastTest = $this->_fastBackend->test($id);
  140. if ($fastTest) {
  141. return $fastTest;
  142. } else {
  143. return $this->_slowBackend->test($id);
  144. }
  145. }
  146. /**
  147. * Save some string datas into a cache record
  148. *
  149. * Note : $data is always "string" (serialization is done by the
  150. * core not by the backend)
  151. *
  152. * @param string $data Datas to cache
  153. * @param string $id Cache id
  154. * @param array $tags Array of strings, the cache record will be tagged by each string entry
  155. * @param int $specificLifetime If != false, set a specific lifetime for this cache record (null => infinite lifetime)
  156. * @param int $priority integer between 0 (very low priority) and 10 (maximum priority) used by some particular backends
  157. * @return boolean true if no problem
  158. */
  159. public function save($data, $id, $tags = array(), $specificLifetime = false, $priority = 8)
  160. {
  161. $usage = $this->_getFastFillingPercentage('saving');
  162. $boolFast = true;
  163. $lifetime = $this->getLifetime($specificLifetime);
  164. $preparedData = $this->_prepareData($data, $lifetime, $priority);
  165. if (($priority > 0) && (10 * $priority >= $usage)) {
  166. $fastLifetime = $this->_getFastLifetime($lifetime, $priority);
  167. $boolFast = $this->_fastBackend->save($preparedData, $id, array(), $fastLifetime);
  168. }
  169. $boolSlow = $this->_slowBackend->save($preparedData, $id, $tags, $lifetime);
  170. return ($boolFast && $boolSlow);
  171. }
  172. /**
  173. * Test if a cache is available for the given id and (if yes) return it (false else)
  174. *
  175. * Note : return value is always "string" (unserialization is done by the core not by the backend)
  176. *
  177. * @param string $id Cache id
  178. * @param boolean $doNotTestCacheValidity If set to true, the cache validity won't be tested
  179. * @return string|false cached datas
  180. */
  181. public function load($id, $doNotTestCacheValidity = false)
  182. {
  183. $res = $this->_fastBackend->load($id, $doNotTestCacheValidity);
  184. if ($res === false) {
  185. $res = $this->_slowBackend->load($id, $doNotTestCacheValidity);
  186. if ($res === false) {
  187. // there is no cache at all for this id
  188. return false;
  189. }
  190. }
  191. $array = unserialize($res);
  192. // maybe, we have to refresh the fast cache ?
  193. if ($this->_options['auto_refresh_fast_cache']) {
  194. if ($array['priority'] == 10) {
  195. // no need to refresh the fast cache with priority = 10
  196. return $array['data'];
  197. }
  198. $newFastLifetime = $this->_getFastLifetime($array['lifetime'], $array['priority'], time() - $array['expire']);
  199. // we have the time to refresh the fast cache
  200. $usage = $this->_getFastFillingPercentage('loading');
  201. if (($array['priority'] > 0) && (10 * $array['priority'] >= $usage)) {
  202. // we can refresh the fast cache
  203. $preparedData = $this->_prepareData($array['data'], $array['lifetime'], $array['priority']);
  204. $this->_fastBackend->save($preparedData, $id, array(), $newFastLifetime);
  205. }
  206. }
  207. return $array['data'];
  208. }
  209. /**
  210. * Remove a cache record
  211. *
  212. * @param string $id Cache id
  213. * @return boolean True if no problem
  214. */
  215. public function remove($id)
  216. {
  217. $boolFast = $this->_fastBackend->remove($id);
  218. $boolSlow = $this->_slowBackend->remove($id);
  219. return $boolFast && $boolSlow;
  220. }
  221. /**
  222. * Clean some cache records
  223. *
  224. * Available modes are :
  225. * Zend_Cache::CLEANING_MODE_ALL (default) => remove all cache entries ($tags is not used)
  226. * Zend_Cache::CLEANING_MODE_OLD => remove too old cache entries ($tags is not used)
  227. * Zend_Cache::CLEANING_MODE_MATCHING_TAG => remove cache entries matching all given tags
  228. * ($tags can be an array of strings or a single string)
  229. * Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG => remove cache entries not {matching one of the given tags}
  230. * ($tags can be an array of strings or a single string)
  231. * Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG => remove cache entries matching any given tags
  232. * ($tags can be an array of strings or a single string)
  233. *
  234. * @param string $mode Clean mode
  235. * @param array $tags Array of tags
  236. * @throws Zend_Cache_Exception
  237. * @return boolean true if no problem
  238. */
  239. public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array())
  240. {
  241. switch($mode) {
  242. case Zend_Cache::CLEANING_MODE_ALL:
  243. $boolFast = $this->_fastBackend->clean(Zend_Cache::CLEANING_MODE_ALL);
  244. $boolSlow = $this->_slowBackend->clean(Zend_Cache::CLEANING_MODE_ALL);
  245. return $boolFast && $boolSlow;
  246. break;
  247. case Zend_Cache::CLEANING_MODE_OLD:
  248. return $this->_slowBackend->clean(Zend_Cache::CLEANING_MODE_OLD);
  249. case Zend_Cache::CLEANING_MODE_MATCHING_TAG:
  250. $ids = $this->_slowBackend->getIdsMatchingTags($tags);
  251. $res = true;
  252. foreach ($ids as $id) {
  253. $bool = $this->remove($id);
  254. $res = $res && $bool;
  255. }
  256. return $res;
  257. break;
  258. case Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG:
  259. $ids = $this->_slowBackend->getIdsNotMatchingTags($tags);
  260. $res = true;
  261. foreach ($ids as $id) {
  262. $bool = $this->remove($id);
  263. $res = $res && $bool;
  264. }
  265. return $res;
  266. break;
  267. case Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG:
  268. $ids = $this->_slowBackend->getIdsMatchingAnyTags($tags);
  269. $res = true;
  270. foreach ($ids as $id) {
  271. $bool = $this->remove($id);
  272. $res = $res && $bool;
  273. }
  274. return $res;
  275. break;
  276. default:
  277. Zend_Cache::throwException('Invalid mode for clean() method');
  278. break;
  279. }
  280. }
  281. /**
  282. * Return an array of stored cache ids
  283. *
  284. * @return array array of stored cache ids (string)
  285. */
  286. public function getIds()
  287. {
  288. return $this->_slowBackend->getIds();
  289. }
  290. /**
  291. * Return an array of stored tags
  292. *
  293. * @return array array of stored tags (string)
  294. */
  295. public function getTags()
  296. {
  297. return $this->_slowBackend->getTags();
  298. }
  299. /**
  300. * Return an array of stored cache ids which match given tags
  301. *
  302. * In case of multiple tags, a logical AND is made between tags
  303. *
  304. * @param array $tags array of tags
  305. * @return array array of matching cache ids (string)
  306. */
  307. public function getIdsMatchingTags($tags = array())
  308. {
  309. return $this->_slowBackend->getIdsMatchingTags($tags);
  310. }
  311. /**
  312. * Return an array of stored cache ids which don't match given tags
  313. *
  314. * In case of multiple tags, a logical OR is made between tags
  315. *
  316. * @param array $tags array of tags
  317. * @return array array of not matching cache ids (string)
  318. */
  319. public function getIdsNotMatchingTags($tags = array())
  320. {
  321. return $this->_slowBackend->getIdsNotMatchingTags($tags);
  322. }
  323. /**
  324. * Return an array of stored cache ids which match any given tags
  325. *
  326. * In case of multiple tags, a logical AND is made between tags
  327. *
  328. * @param array $tags array of tags
  329. * @return array array of any matching cache ids (string)
  330. */
  331. public function getIdsMatchingAnyTags($tags = array())
  332. {
  333. return $this->_slowBackend->getIdsMatchingAnyTags($tags);
  334. }
  335. /**
  336. * Return the filling percentage of the backend storage
  337. *
  338. * @return int integer between 0 and 100
  339. */
  340. public function getFillingPercentage()
  341. {
  342. return $this->_slowBackend->getFillingPercentage();
  343. }
  344. /**
  345. * Return an array of metadatas for the given cache id
  346. *
  347. * The array must include these keys :
  348. * - expire : the expire timestamp
  349. * - tags : a string array of tags
  350. * - mtime : timestamp of last modification time
  351. *
  352. * @param string $id cache id
  353. * @return array array of metadatas (false if the cache id is not found)
  354. */
  355. public function getMetadatas($id)
  356. {
  357. return $this->_slowBackend->getMetadatas($id);
  358. }
  359. /**
  360. * Give (if possible) an extra lifetime to the given cache id
  361. *
  362. * @param string $id cache id
  363. * @param int $extraLifetime
  364. * @return boolean true if ok
  365. */
  366. public function touch($id, $extraLifetime)
  367. {
  368. return $this->_slowBackend->touch($id, $extraLifetime);
  369. }
  370. /**
  371. * Return an associative array of capabilities (booleans) of the backend
  372. *
  373. * The array must include these keys :
  374. * - automatic_cleaning (is automating cleaning necessary)
  375. * - tags (are tags supported)
  376. * - expired_read (is it possible to read expired cache records
  377. * (for doNotTestCacheValidity option for example))
  378. * - priority does the backend deal with priority when saving
  379. * - infinite_lifetime (is infinite lifetime can work with this backend)
  380. * - get_list (is it possible to get the list of cache ids and the complete list of tags)
  381. *
  382. * @return array associative of with capabilities
  383. */
  384. public function getCapabilities()
  385. {
  386. $slowBackendCapabilities = $this->_slowBackend->getCapabilities();
  387. return array(
  388. 'automatic_cleaning' => $slowBackendCapabilities['automatic_cleaning'],
  389. 'tags' => $slowBackendCapabilities['tags'],
  390. 'expired_read' => $slowBackendCapabilities['expired_read'],
  391. 'priority' => $slowBackendCapabilities['priority'],
  392. 'infinite_lifetime' => $slowBackendCapabilities['infinite_lifetime'],
  393. 'get_list' => $slowBackendCapabilities['get_list']
  394. );
  395. }
  396. /**
  397. * Prepare a serialized array to store datas and metadatas informations
  398. *
  399. * @param string $data data to store
  400. * @param int $lifetime original lifetime
  401. * @param int $priority priority
  402. * @return string serialize array to store into cache
  403. */
  404. private function _prepareData($data, $lifetime, $priority)
  405. {
  406. $lt = $lifetime;
  407. if ($lt === null) {
  408. $lt = 9999999999;
  409. }
  410. return serialize(array(
  411. 'data' => $data,
  412. 'lifetime' => $lifetime,
  413. 'expire' => time() + $lt,
  414. 'priority' => $priority
  415. ));
  416. }
  417. /**
  418. * Compute and return the lifetime for the fast backend
  419. *
  420. * @param int $lifetime original lifetime
  421. * @param int $priority priority
  422. * @param int $maxLifetime maximum lifetime
  423. * @return int lifetime for the fast backend
  424. */
  425. private function _getFastLifetime($lifetime, $priority, $maxLifetime = null)
  426. {
  427. if ($lifetime === null) {
  428. // if lifetime is null, we have an infinite lifetime
  429. // we need to use arbitrary lifetimes
  430. $fastLifetime = (int) (2592000 / (11 - $priority));
  431. } else {
  432. $fastLifetime = (int) ($lifetime / (11 - $priority));
  433. }
  434. if (($maxLifetime !== null) && ($maxLifetime >= 0)) {
  435. if ($fastLifetime > $maxLifetime) {
  436. return $maxLifetime;
  437. }
  438. }
  439. return $fastLifetime;
  440. }
  441. /**
  442. * PUBLIC METHOD FOR UNIT TESTING ONLY !
  443. *
  444. * Force a cache record to expire
  445. *
  446. * @param string $id cache id
  447. */
  448. public function ___expire($id)
  449. {
  450. $this->_fastBackend->remove($id);
  451. $this->_slowBackend->___expire($id);
  452. }
  453. private function _getFastFillingPercentage($mode)
  454. {
  455. if ($mode == 'saving') {
  456. // mode saving
  457. if ($this->_fastBackendFillingPercentage === null) {
  458. $this->_fastBackendFillingPercentage = $this->_fastBackend->getFillingPercentage();
  459. } else {
  460. $rand = rand(1, $this->_options['stats_update_factor']);
  461. if ($rand == 1) {
  462. // we force a refresh
  463. $this->_fastBackendFillingPercentage = $this->_fastBackend->getFillingPercentage();
  464. }
  465. }
  466. } else {
  467. // mode loading
  468. // we compute the percentage only if it's not available in cache
  469. if ($this->_fastBackendFillingPercentage === null) {
  470. $this->_fastBackendFillingPercentage = $this->_fastBackend->getFillingPercentage();
  471. }
  472. }
  473. return $this->_fastBackendFillingPercentage;
  474. }
  475. }