TwoLevels.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  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-2009 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-2009 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. private $_slowBackend;
  92. /**
  93. * Fast Backend
  94. *
  95. * @var Zend_Cache_Backend
  96. */
  97. private $_fastBackend;
  98. /**
  99. * Cache for the fast backend filling percentage
  100. *
  101. * @var int
  102. */
  103. private $_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. $this->_fastBackend->remove($id);
  218. return $this->_slowBackend->remove($id);
  219. }
  220. /**
  221. * Clean some cache records
  222. *
  223. * Available modes are :
  224. * Zend_Cache::CLEANING_MODE_ALL (default) => remove all cache entries ($tags is not used)
  225. * Zend_Cache::CLEANING_MODE_OLD => remove too old cache entries ($tags is not used)
  226. * Zend_Cache::CLEANING_MODE_MATCHING_TAG => remove cache entries matching all given tags
  227. * ($tags can be an array of strings or a single string)
  228. * Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG => remove cache entries not {matching one of the given tags}
  229. * ($tags can be an array of strings or a single string)
  230. * Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG => remove cache entries matching any given tags
  231. * ($tags can be an array of strings or a single string)
  232. *
  233. * @param string $mode Clean mode
  234. * @param array $tags Array of tags
  235. * @throws Zend_Cache_Exception
  236. * @return boolean true if no problem
  237. */
  238. public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array())
  239. {
  240. switch($mode) {
  241. case Zend_Cache::CLEANING_MODE_ALL:
  242. $boolFast = $this->_fastBackend->clean(Zend_Cache::CLEANING_MODE_ALL);
  243. $boolSlow = $this->_slowBackend->clean(Zend_Cache::CLEANING_MODE_ALL);
  244. return $boolFast && $boolSlow;
  245. break;
  246. case Zend_Cache::CLEANING_MODE_OLD:
  247. return $this->_slowBackend->clean(Zend_Cache::CLEANING_MODE_OLD);
  248. case Zend_Cache::CLEANING_MODE_MATCHING_TAG:
  249. $ids = $this->_slowBackend->getIdsMatchingTags($tags);
  250. $res = true;
  251. foreach ($ids as $id) {
  252. $res = $res && $this->_slowBackend->remove($id) && $this->_fastBackend->remove($id);
  253. }
  254. return $res;
  255. break;
  256. case Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG:
  257. $ids = $this->_slowBackend->getIdsNotMatchingTags($tags);
  258. $res = true;
  259. foreach ($ids as $id) {
  260. $res = $res && $this->_slowBackend->remove($id) && $this->_fastBackend->remove($id);
  261. }
  262. return $res;
  263. break;
  264. case Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG:
  265. $ids = $this->_slowBackend->getIdsMatchingAnyTags($tags);
  266. $res = true;
  267. foreach ($ids as $id) {
  268. $res = $res && $this->_slowBackend->remove($id) && $this->_fastBackend->remove($id);
  269. }
  270. return $res;
  271. break;
  272. default:
  273. Zend_Cache::throwException('Invalid mode for clean() method');
  274. break;
  275. }
  276. }
  277. /**
  278. * Return an array of stored cache ids
  279. *
  280. * @return array array of stored cache ids (string)
  281. */
  282. public function getIds()
  283. {
  284. return $this->_slowBackend->getIds();
  285. }
  286. /**
  287. * Return an array of stored tags
  288. *
  289. * @return array array of stored tags (string)
  290. */
  291. public function getTags()
  292. {
  293. return $this->_slowBackend->getTags();
  294. }
  295. /**
  296. * Return an array of stored cache ids which match given tags
  297. *
  298. * In case of multiple tags, a logical AND is made between tags
  299. *
  300. * @param array $tags array of tags
  301. * @return array array of matching cache ids (string)
  302. */
  303. public function getIdsMatchingTags($tags = array())
  304. {
  305. return $this->_slowBackend->getIdsMatchingTags($tags);
  306. }
  307. /**
  308. * Return an array of stored cache ids which don't match given tags
  309. *
  310. * In case of multiple tags, a logical OR is made between tags
  311. *
  312. * @param array $tags array of tags
  313. * @return array array of not matching cache ids (string)
  314. */
  315. public function getIdsNotMatchingTags($tags = array())
  316. {
  317. return $this->_slowBackend->getIdsNotMatchingTags($tags);
  318. }
  319. /**
  320. * Return an array of stored cache ids which match any given tags
  321. *
  322. * In case of multiple tags, a logical AND is made between tags
  323. *
  324. * @param array $tags array of tags
  325. * @return array array of any matching cache ids (string)
  326. */
  327. public function getIdsMatchingAnyTags($tags = array())
  328. {
  329. return $this->_slowBackend->getIdsMatchingAnyTags($tags);
  330. }
  331. /**
  332. * Return the filling percentage of the backend storage
  333. *
  334. * @return int integer between 0 and 100
  335. */
  336. public function getFillingPercentage()
  337. {
  338. return $this->_slowBackend->getFillingPercentage();
  339. }
  340. /**
  341. * Return an array of metadatas for the given cache id
  342. *
  343. * The array must include these keys :
  344. * - expire : the expire timestamp
  345. * - tags : a string array of tags
  346. * - mtime : timestamp of last modification time
  347. *
  348. * @param string $id cache id
  349. * @return array array of metadatas (false if the cache id is not found)
  350. */
  351. public function getMetadatas($id)
  352. {
  353. return $this->_slowBackend->getMetadatas($id);
  354. }
  355. /**
  356. * Give (if possible) an extra lifetime to the given cache id
  357. *
  358. * @param string $id cache id
  359. * @param int $extraLifetime
  360. * @return boolean true if ok
  361. */
  362. public function touch($id, $extraLifetime)
  363. {
  364. return $this->_slowBackend->touch($id, $extraLifetime);
  365. }
  366. /**
  367. * Return an associative array of capabilities (booleans) of the backend
  368. *
  369. * The array must include these keys :
  370. * - automatic_cleaning (is automating cleaning necessary)
  371. * - tags (are tags supported)
  372. * - expired_read (is it possible to read expired cache records
  373. * (for doNotTestCacheValidity option for example))
  374. * - priority does the backend deal with priority when saving
  375. * - infinite_lifetime (is infinite lifetime can work with this backend)
  376. * - get_list (is it possible to get the list of cache ids and the complete list of tags)
  377. *
  378. * @return array associative of with capabilities
  379. */
  380. public function getCapabilities()
  381. {
  382. $slowBackendCapabilities = $this->_slowBackend->getCapabilities();
  383. return array(
  384. 'automatic_cleaning' => $slowBackendCapabilities['automatic_cleaning'],
  385. 'tags' => $slowBackendCapabilities['tags'],
  386. 'expired_read' => $slowBackendCapabilities['expired_read'],
  387. 'priority' => $slowBackendCapabilities['priority'],
  388. 'infinite_lifetime' => $slowBackendCapabilities['infinite_lifetime'],
  389. 'get_list' => $slowBackendCapabilities['get_list']
  390. );
  391. }
  392. /**
  393. * Prepare a serialized array to store datas and metadatas informations
  394. *
  395. * @param string $data data to store
  396. * @param int $lifetime original lifetime
  397. * @param int $priority priority
  398. * @return string serialize array to store into cache
  399. */
  400. private function _prepareData($data, $lifetime, $priority)
  401. {
  402. $lt = $lifetime;
  403. if ($lt === null) {
  404. $lt = 9999999999;
  405. }
  406. return serialize(array(
  407. 'data' => $data,
  408. 'lifetime' => $lifetime,
  409. 'expire' => time() + $lt,
  410. 'priority' => $priority
  411. ));
  412. }
  413. /**
  414. * Compute and return the lifetime for the fast backend
  415. *
  416. * @param int $lifetime original lifetime
  417. * @param int $priority priority
  418. * @param int $maxLifetime maximum lifetime
  419. * @return int lifetime for the fast backend
  420. */
  421. private function _getFastLifetime($lifetime, $priority, $maxLifetime = null)
  422. {
  423. if ($lifetime === null) {
  424. // if lifetime is null, we have an infinite lifetime
  425. // we need to use arbitrary lifetimes
  426. $fastLifetime = (int) (2592000 / (11 - $priority));
  427. } else {
  428. $fastLifetime = (int) ($lifetime / (11 - $priority));
  429. }
  430. if (($maxLifetime !== null) && ($maxLifetime >= 0)) {
  431. if ($fastLifetime > $maxLifetime) {
  432. return $maxLifetime;
  433. }
  434. }
  435. return $fastLifetime;
  436. }
  437. /**
  438. * PUBLIC METHOD FOR UNIT TESTING ONLY !
  439. *
  440. * Force a cache record to expire
  441. *
  442. * @param string $id cache id
  443. */
  444. public function ___expire($id)
  445. {
  446. $this->_fastBackend->remove($id);
  447. $this->_slowBackend->___expire($id);
  448. }
  449. private function _getFastFillingPercentage($mode)
  450. {
  451. if ($mode == 'saving') {
  452. // mode saving
  453. if ($this->_fastBackendFillingPercentage === null) {
  454. $this->_fastBackendFillingPercentage = $this->_fastBackend->getFillingPercentage();
  455. } else {
  456. $rand = rand(1, $this->_options['stats_update_factor']);
  457. if ($rand == 1) {
  458. // we force a refresh
  459. $this->_fastBackendFillingPercentage = $this->_fastBackend->getFillingPercentage();
  460. }
  461. }
  462. } else {
  463. // mode loading
  464. // we compute the percentage only if it's not available in cache
  465. if ($this->_fastBackendFillingPercentage === null) {
  466. $this->_fastBackendFillingPercentage = $this->_fastBackend->getFillingPercentage();
  467. }
  468. }
  469. return $this->_fastBackendFillingPercentage;
  470. }
  471. }