TwoLevels.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  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$
  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. } elseif ($this->_options['slow_backend'] instanceof Zend_Cache_Backend_ExtendedInterface) {
  117. $this->_slowBackend = $this->_options['slow_backend'];
  118. } else {
  119. $this->_slowBackend = Zend_Cache::_makeBackend(
  120. $this->_options['slow_backend'],
  121. $this->_options['slow_backend_options'],
  122. $this->_options['slow_backend_custom_naming'],
  123. $this->_options['slow_backend_autoload']
  124. );
  125. if (!in_array('Zend_Cache_Backend_ExtendedInterface', class_implements($this->_slowBackend))) {
  126. Zend_Cache::throwException('slow_backend must implement the Zend_Cache_Backend_ExtendedInterface interface');
  127. }
  128. }
  129. if ($this->_options['fast_backend'] === null) {
  130. Zend_Cache::throwException('fast_backend option has to set');
  131. } elseif ($this->_options['fast_backend'] instanceof Zend_Cache_Backend_ExtendedInterface) {
  132. $this->_fastBackend = $this->_options['fast_backend'];
  133. } else {
  134. $this->_fastBackend = Zend_Cache::_makeBackend(
  135. $this->_options['fast_backend'],
  136. $this->_options['fast_backend_options'],
  137. $this->_options['fast_backend_custom_naming'],
  138. $this->_options['fast_backend_autoload']
  139. );
  140. if (!in_array('Zend_Cache_Backend_ExtendedInterface', class_implements($this->_fastBackend))) {
  141. Zend_Cache::throwException('fast_backend must implement the Zend_Cache_Backend_ExtendedInterface interface');
  142. }
  143. }
  144. $this->_slowBackend->setDirectives($this->_directives);
  145. $this->_fastBackend->setDirectives($this->_directives);
  146. }
  147. /**
  148. * Test if a cache is available or not (for the given id)
  149. *
  150. * @param string $id cache id
  151. * @return mixed|false (a cache is not available) or "last modified" timestamp (int) of the available cache record
  152. */
  153. public function test($id)
  154. {
  155. $fastTest = $this->_fastBackend->test($id);
  156. if ($fastTest) {
  157. return $fastTest;
  158. } else {
  159. return $this->_slowBackend->test($id);
  160. }
  161. }
  162. /**
  163. * Save some string datas into a cache record
  164. *
  165. * Note : $data is always "string" (serialization is done by the
  166. * core not by the backend)
  167. *
  168. * @param string $data Datas to cache
  169. * @param string $id Cache id
  170. * @param array $tags Array of strings, the cache record will be tagged by each string entry
  171. * @param int $specificLifetime If != false, set a specific lifetime for this cache record (null => infinite lifetime)
  172. * @param int $priority integer between 0 (very low priority) and 10 (maximum priority) used by some particular backends
  173. * @return boolean true if no problem
  174. */
  175. public function save($data, $id, $tags = array(), $specificLifetime = false, $priority = 8)
  176. {
  177. $usage = $this->_getFastFillingPercentage('saving');
  178. $boolFast = true;
  179. $lifetime = $this->getLifetime($specificLifetime);
  180. $preparedData = $this->_prepareData($data, $lifetime, $priority);
  181. if (($priority > 0) && (10 * $priority >= $usage)) {
  182. $fastLifetime = $this->_getFastLifetime($lifetime, $priority);
  183. $boolFast = $this->_fastBackend->save($preparedData, $id, array(), $fastLifetime);
  184. $boolSlow = $this->_slowBackend->save($preparedData, $id, $tags, $lifetime);
  185. } else {
  186. $boolSlow = $this->_slowBackend->save($preparedData, $id, $tags, $lifetime);
  187. if ($boolSlow === true) {
  188. $boolFast = $this->_fastBackend->remove($id);
  189. }
  190. }
  191. return ($boolFast && $boolSlow);
  192. }
  193. /**
  194. * Test if a cache is available for the given id and (if yes) return it (false else)
  195. *
  196. * Note : return value is always "string" (unserialization is done by the core not by the backend)
  197. *
  198. * @param string $id Cache id
  199. * @param boolean $doNotTestCacheValidity If set to true, the cache validity won't be tested
  200. * @return string|false cached datas
  201. */
  202. public function load($id, $doNotTestCacheValidity = false)
  203. {
  204. $res = $this->_fastBackend->load($id, $doNotTestCacheValidity);
  205. if ($res === false) {
  206. $res = $this->_slowBackend->load($id, $doNotTestCacheValidity);
  207. if ($res === false) {
  208. // there is no cache at all for this id
  209. return false;
  210. }
  211. }
  212. $array = unserialize($res);
  213. // maybe, we have to refresh the fast cache ?
  214. if ($this->_options['auto_refresh_fast_cache']) {
  215. if ($array['priority'] == 10) {
  216. // no need to refresh the fast cache with priority = 10
  217. return $array['data'];
  218. }
  219. $newFastLifetime = $this->_getFastLifetime($array['lifetime'], $array['priority'], time() - $array['expire']);
  220. // we have the time to refresh the fast cache
  221. $usage = $this->_getFastFillingPercentage('loading');
  222. if (($array['priority'] > 0) && (10 * $array['priority'] >= $usage)) {
  223. // we can refresh the fast cache
  224. $preparedData = $this->_prepareData($array['data'], $array['lifetime'], $array['priority']);
  225. $this->_fastBackend->save($preparedData, $id, array(), $newFastLifetime);
  226. }
  227. }
  228. return $array['data'];
  229. }
  230. /**
  231. * Remove a cache record
  232. *
  233. * @param string $id Cache id
  234. * @return boolean True if no problem
  235. */
  236. public function remove($id)
  237. {
  238. $boolFast = $this->_fastBackend->remove($id);
  239. $boolSlow = $this->_slowBackend->remove($id);
  240. return $boolFast && $boolSlow;
  241. }
  242. /**
  243. * Clean some cache records
  244. *
  245. * Available modes are :
  246. * Zend_Cache::CLEANING_MODE_ALL (default) => remove all cache entries ($tags is not used)
  247. * Zend_Cache::CLEANING_MODE_OLD => remove too old cache entries ($tags is not used)
  248. * Zend_Cache::CLEANING_MODE_MATCHING_TAG => remove cache entries matching all given tags
  249. * ($tags can be an array of strings or a single string)
  250. * Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG => remove cache entries not {matching one of the given tags}
  251. * ($tags can be an array of strings or a single string)
  252. * Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG => remove cache entries matching any given tags
  253. * ($tags can be an array of strings or a single string)
  254. *
  255. * @param string $mode Clean mode
  256. * @param array $tags Array of tags
  257. * @throws Zend_Cache_Exception
  258. * @return boolean true if no problem
  259. */
  260. public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array())
  261. {
  262. switch($mode) {
  263. case Zend_Cache::CLEANING_MODE_ALL:
  264. $boolFast = $this->_fastBackend->clean(Zend_Cache::CLEANING_MODE_ALL);
  265. $boolSlow = $this->_slowBackend->clean(Zend_Cache::CLEANING_MODE_ALL);
  266. return $boolFast && $boolSlow;
  267. break;
  268. case Zend_Cache::CLEANING_MODE_OLD:
  269. return $this->_slowBackend->clean(Zend_Cache::CLEANING_MODE_OLD);
  270. case Zend_Cache::CLEANING_MODE_MATCHING_TAG:
  271. $ids = $this->_slowBackend->getIdsMatchingTags($tags);
  272. $res = true;
  273. foreach ($ids as $id) {
  274. $bool = $this->remove($id);
  275. $res = $res && $bool;
  276. }
  277. return $res;
  278. break;
  279. case Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG:
  280. $ids = $this->_slowBackend->getIdsNotMatchingTags($tags);
  281. $res = true;
  282. foreach ($ids as $id) {
  283. $bool = $this->remove($id);
  284. $res = $res && $bool;
  285. }
  286. return $res;
  287. break;
  288. case Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG:
  289. $ids = $this->_slowBackend->getIdsMatchingAnyTags($tags);
  290. $res = true;
  291. foreach ($ids as $id) {
  292. $bool = $this->remove($id);
  293. $res = $res && $bool;
  294. }
  295. return $res;
  296. break;
  297. default:
  298. Zend_Cache::throwException('Invalid mode for clean() method');
  299. break;
  300. }
  301. }
  302. /**
  303. * Return an array of stored cache ids
  304. *
  305. * @return array array of stored cache ids (string)
  306. */
  307. public function getIds()
  308. {
  309. return $this->_slowBackend->getIds();
  310. }
  311. /**
  312. * Return an array of stored tags
  313. *
  314. * @return array array of stored tags (string)
  315. */
  316. public function getTags()
  317. {
  318. return $this->_slowBackend->getTags();
  319. }
  320. /**
  321. * Return an array of stored cache ids which match given tags
  322. *
  323. * In case of multiple tags, a logical AND is made between tags
  324. *
  325. * @param array $tags array of tags
  326. * @return array array of matching cache ids (string)
  327. */
  328. public function getIdsMatchingTags($tags = array())
  329. {
  330. return $this->_slowBackend->getIdsMatchingTags($tags);
  331. }
  332. /**
  333. * Return an array of stored cache ids which don't match given tags
  334. *
  335. * In case of multiple tags, a logical OR is made between tags
  336. *
  337. * @param array $tags array of tags
  338. * @return array array of not matching cache ids (string)
  339. */
  340. public function getIdsNotMatchingTags($tags = array())
  341. {
  342. return $this->_slowBackend->getIdsNotMatchingTags($tags);
  343. }
  344. /**
  345. * Return an array of stored cache ids which match any given tags
  346. *
  347. * In case of multiple tags, a logical AND is made between tags
  348. *
  349. * @param array $tags array of tags
  350. * @return array array of any matching cache ids (string)
  351. */
  352. public function getIdsMatchingAnyTags($tags = array())
  353. {
  354. return $this->_slowBackend->getIdsMatchingAnyTags($tags);
  355. }
  356. /**
  357. * Return the filling percentage of the backend storage
  358. *
  359. * @return int integer between 0 and 100
  360. */
  361. public function getFillingPercentage()
  362. {
  363. return $this->_slowBackend->getFillingPercentage();
  364. }
  365. /**
  366. * Return an array of metadatas for the given cache id
  367. *
  368. * The array must include these keys :
  369. * - expire : the expire timestamp
  370. * - tags : a string array of tags
  371. * - mtime : timestamp of last modification time
  372. *
  373. * @param string $id cache id
  374. * @return array array of metadatas (false if the cache id is not found)
  375. */
  376. public function getMetadatas($id)
  377. {
  378. return $this->_slowBackend->getMetadatas($id);
  379. }
  380. /**
  381. * Give (if possible) an extra lifetime to the given cache id
  382. *
  383. * @param string $id cache id
  384. * @param int $extraLifetime
  385. * @return boolean true if ok
  386. */
  387. public function touch($id, $extraLifetime)
  388. {
  389. return $this->_slowBackend->touch($id, $extraLifetime);
  390. }
  391. /**
  392. * Return an associative array of capabilities (booleans) of the backend
  393. *
  394. * The array must include these keys :
  395. * - automatic_cleaning (is automating cleaning necessary)
  396. * - tags (are tags supported)
  397. * - expired_read (is it possible to read expired cache records
  398. * (for doNotTestCacheValidity option for example))
  399. * - priority does the backend deal with priority when saving
  400. * - infinite_lifetime (is infinite lifetime can work with this backend)
  401. * - get_list (is it possible to get the list of cache ids and the complete list of tags)
  402. *
  403. * @return array associative of with capabilities
  404. */
  405. public function getCapabilities()
  406. {
  407. $slowBackendCapabilities = $this->_slowBackend->getCapabilities();
  408. return array(
  409. 'automatic_cleaning' => $slowBackendCapabilities['automatic_cleaning'],
  410. 'tags' => $slowBackendCapabilities['tags'],
  411. 'expired_read' => $slowBackendCapabilities['expired_read'],
  412. 'priority' => $slowBackendCapabilities['priority'],
  413. 'infinite_lifetime' => $slowBackendCapabilities['infinite_lifetime'],
  414. 'get_list' => $slowBackendCapabilities['get_list']
  415. );
  416. }
  417. /**
  418. * Prepare a serialized array to store datas and metadatas informations
  419. *
  420. * @param string $data data to store
  421. * @param int $lifetime original lifetime
  422. * @param int $priority priority
  423. * @return string serialize array to store into cache
  424. */
  425. private function _prepareData($data, $lifetime, $priority)
  426. {
  427. $lt = $lifetime;
  428. if ($lt === null) {
  429. $lt = 9999999999;
  430. }
  431. return serialize(array(
  432. 'data' => $data,
  433. 'lifetime' => $lifetime,
  434. 'expire' => time() + $lt,
  435. 'priority' => $priority
  436. ));
  437. }
  438. /**
  439. * Compute and return the lifetime for the fast backend
  440. *
  441. * @param int $lifetime original lifetime
  442. * @param int $priority priority
  443. * @param int $maxLifetime maximum lifetime
  444. * @return int lifetime for the fast backend
  445. */
  446. private function _getFastLifetime($lifetime, $priority, $maxLifetime = null)
  447. {
  448. if ($lifetime === null) {
  449. // if lifetime is null, we have an infinite lifetime
  450. // we need to use arbitrary lifetimes
  451. $fastLifetime = (int) (2592000 / (11 - $priority));
  452. } else {
  453. $fastLifetime = (int) ($lifetime / (11 - $priority));
  454. }
  455. if (($maxLifetime !== null) && ($maxLifetime >= 0)) {
  456. if ($fastLifetime > $maxLifetime) {
  457. return $maxLifetime;
  458. }
  459. }
  460. return $fastLifetime;
  461. }
  462. /**
  463. * PUBLIC METHOD FOR UNIT TESTING ONLY !
  464. *
  465. * Force a cache record to expire
  466. *
  467. * @param string $id cache id
  468. */
  469. public function ___expire($id)
  470. {
  471. $this->_fastBackend->remove($id);
  472. $this->_slowBackend->___expire($id);
  473. }
  474. private function _getFastFillingPercentage($mode)
  475. {
  476. if ($mode == 'saving') {
  477. // mode saving
  478. if ($this->_fastBackendFillingPercentage === null) {
  479. $this->_fastBackendFillingPercentage = $this->_fastBackend->getFillingPercentage();
  480. } else {
  481. $rand = rand(1, $this->_options['stats_update_factor']);
  482. if ($rand == 1) {
  483. // we force a refresh
  484. $this->_fastBackendFillingPercentage = $this->_fastBackend->getFillingPercentage();
  485. }
  486. }
  487. } else {
  488. // mode loading
  489. // we compute the percentage only if it's not available in cache
  490. if ($this->_fastBackendFillingPercentage === null) {
  491. $this->_fastBackendFillingPercentage = $this->_fastBackend->getFillingPercentage();
  492. }
  493. }
  494. return $this->_fastBackendFillingPercentage;
  495. }
  496. }