*prechod na novsiu verziu ZF
[sport-group.git] / library / Zend / Cache / Backend / TwoLevels.php
blobb340645f6c4f4b992280da00507ac2c593c8a655
1 <?php
2 /**
3 * Zend Framework
5 * LICENSE
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.
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: TwoLevels.php 17741 2009-08-22 02:58:33Z yoshida@zend.co.jp $
24 /**
25 * @see Zend_Cache_Backend_ExtendedInterface
27 require_once 'Zend/Cache/Backend/ExtendedInterface.php';
29 /**
30 * @see Zend_Cache_Backend
32 require_once 'Zend/Cache/Backend.php';
35 /**
36 * @package Zend_Cache
37 * @subpackage Zend_Cache_Backend
38 * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
39 * @license http://framework.zend.com/license/new-bsd New BSD License
42 class Zend_Cache_Backend_TwoLevels extends Zend_Cache_Backend implements Zend_Cache_Backend_ExtendedInterface
44 /**
45 * Available options
47 * =====> (string) slow_backend :
48 * - Slow backend name
49 * - Must implement the Zend_Cache_Backend_ExtendedInterface
50 * - Should provide a big storage
52 * =====> (string) fast_backend :
53 * - Flow backend name
54 * - Must implement the Zend_Cache_Backend_ExtendedInterface
55 * - Must be much faster than slow_backend
57 * =====> (array) slow_backend_options :
58 * - Slow backend options (see corresponding backend)
60 * =====> (array) fast_backend_options :
61 * - Fast backend options (see corresponding backend)
63 * =====> (int) stats_update_factor :
64 * - Disable / Tune the computation of the fast backend filling percentage
65 * - When saving a record into cache :
66 * 1 => systematic computation of the fast backend filling percentage
67 * x (integer) > 1 => computation of the fast backend filling percentage randomly 1 times on x cache write
69 * =====> (boolean) slow_backend_custom_naming :
70 * =====> (boolean) fast_backend_custom_naming :
71 * =====> (boolean) slow_backend_autoload :
72 * =====> (boolean) fast_backend_autoload :
73 * - See Zend_Cache::factory() method
75 * =====> (boolean) auto_refresh_fast_cache
76 * - If true, auto refresh the fast cache when a cache record is hit
78 * @var array available options
80 protected $_options = array(
81 'slow_backend' => 'File',
82 'fast_backend' => 'Apc',
83 'slow_backend_options' => array(),
84 'fast_backend_options' => array(),
85 'stats_update_factor' => 10,
86 'slow_backend_custom_naming' => false,
87 'fast_backend_custom_naming' => false,
88 'slow_backend_autoload' => false,
89 'fast_backend_autoload' => false,
90 'auto_refresh_fast_cache' => true
93 /**
94 * Slow Backend
96 * @var Zend_Cache_Backend
98 private $_slowBackend;
101 * Fast Backend
103 * @var Zend_Cache_Backend
105 private $_fastBackend;
108 * Cache for the fast backend filling percentage
110 * @var int
112 private $_fastBackendFillingPercentage = null;
115 * Constructor
117 * @param array $options Associative array of options
118 * @throws Zend_Cache_Exception
119 * @return void
121 public function __construct(array $options = array())
123 parent::__construct($options);
124 if ($this->_options['slow_backend'] === null) {
125 Zend_Cache::throwException('slow_backend option has to set');
127 if ($this->_options['fast_backend'] === null) {
128 Zend_Cache::throwException('fast_backend option has to set');
130 $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']);
131 $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']);
132 if (!in_array('Zend_Cache_Backend_ExtendedInterface', class_implements($this->_slowBackend))) {
133 Zend_Cache::throwException('slow_backend must implement the Zend_Cache_Backend_ExtendedInterface interface');
135 if (!in_array('Zend_Cache_Backend_ExtendedInterface', class_implements($this->_fastBackend))) {
136 Zend_Cache::throwException('fast_backend must implement the Zend_Cache_Backend_ExtendedInterface interface');
138 $this->_slowBackend->setDirectives($this->_directives);
139 $this->_fastBackend->setDirectives($this->_directives);
143 * Test if a cache is available or not (for the given id)
145 * @param string $id cache id
146 * @return mixed|false (a cache is not available) or "last modified" timestamp (int) of the available cache record
148 public function test($id)
150 $fastTest = $this->_fastBackend->test($id);
151 if ($fastTest) {
152 return $fastTest;
153 } else {
154 return $this->_slowBackend->test($id);
159 * Save some string datas into a cache record
161 * Note : $data is always "string" (serialization is done by the
162 * core not by the backend)
164 * @param string $data Datas to cache
165 * @param string $id Cache id
166 * @param array $tags Array of strings, the cache record will be tagged by each string entry
167 * @param int $specificLifetime If != false, set a specific lifetime for this cache record (null => infinite lifetime)
168 * @param int $priority integer between 0 (very low priority) and 10 (maximum priority) used by some particular backends
169 * @return boolean true if no problem
171 public function save($data, $id, $tags = array(), $specificLifetime = false, $priority = 8)
173 $usage = $this->_getFastFillingPercentage('saving');
174 $boolFast = true;
175 $lifetime = $this->getLifetime($specificLifetime);
176 $preparedData = $this->_prepareData($data, $lifetime, $priority);
177 if (($priority > 0) && (10 * $priority >= $usage)) {
178 $fastLifetime = $this->_getFastLifetime($lifetime, $priority);
179 $boolFast = $this->_fastBackend->save($preparedData, $id, array(), $fastLifetime);
181 $boolSlow = $this->_slowBackend->save($preparedData, $id, $tags, $lifetime);
182 return ($boolFast && $boolSlow);
186 * Test if a cache is available for the given id and (if yes) return it (false else)
188 * Note : return value is always "string" (unserialization is done by the core not by the backend)
190 * @param string $id Cache id
191 * @param boolean $doNotTestCacheValidity If set to true, the cache validity won't be tested
192 * @return string|false cached datas
194 public function load($id, $doNotTestCacheValidity = false)
196 $res = $this->_fastBackend->load($id, $doNotTestCacheValidity);
197 if ($res === false) {
198 $res = $this->_slowBackend->load($id, $doNotTestCacheValidity);
199 if ($res === false) {
200 // there is no cache at all for this id
201 return false;
204 $array = unserialize($res);
205 // maybe, we have to refresh the fast cache ?
206 if ($this->_options['auto_refresh_fast_cache']) {
207 if ($array['priority'] == 10) {
208 // no need to refresh the fast cache with priority = 10
209 return $array['data'];
211 $newFastLifetime = $this->_getFastLifetime($array['lifetime'], $array['priority'], time() - $array['expire']);
212 // we have the time to refresh the fast cache
213 $usage = $this->_getFastFillingPercentage('loading');
214 if (($array['priority'] > 0) && (10 * $array['priority'] >= $usage)) {
215 // we can refresh the fast cache
216 $preparedData = $this->_prepareData($array['data'], $array['lifetime'], $array['priority']);
217 $this->_fastBackend->save($preparedData, $id, array(), $newFastLifetime);
220 return $array['data'];
224 * Remove a cache record
226 * @param string $id Cache id
227 * @return boolean True if no problem
229 public function remove($id)
231 $boolFast = $this->_fastBackend->remove($id);
232 $boolSlow = $this->_slowBackend->remove($id);
233 return $boolFast && $boolSlow;
237 * Clean some cache records
239 * Available modes are :
240 * Zend_Cache::CLEANING_MODE_ALL (default) => remove all cache entries ($tags is not used)
241 * Zend_Cache::CLEANING_MODE_OLD => remove too old cache entries ($tags is not used)
242 * Zend_Cache::CLEANING_MODE_MATCHING_TAG => remove cache entries matching all given tags
243 * ($tags can be an array of strings or a single string)
244 * Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG => remove cache entries not {matching one of the given tags}
245 * ($tags can be an array of strings or a single string)
246 * Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG => remove cache entries matching any given tags
247 * ($tags can be an array of strings or a single string)
249 * @param string $mode Clean mode
250 * @param array $tags Array of tags
251 * @throws Zend_Cache_Exception
252 * @return boolean true if no problem
254 public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array())
256 switch($mode) {
257 case Zend_Cache::CLEANING_MODE_ALL:
258 $boolFast = $this->_fastBackend->clean(Zend_Cache::CLEANING_MODE_ALL);
259 $boolSlow = $this->_slowBackend->clean(Zend_Cache::CLEANING_MODE_ALL);
260 return $boolFast && $boolSlow;
261 break;
262 case Zend_Cache::CLEANING_MODE_OLD:
263 return $this->_slowBackend->clean(Zend_Cache::CLEANING_MODE_OLD);
264 case Zend_Cache::CLEANING_MODE_MATCHING_TAG:
265 $ids = $this->_slowBackend->getIdsMatchingTags($tags);
266 $res = true;
267 foreach ($ids as $id) {
268 $bool = $this->remove($id);
269 $res = $res && $bool;
271 return $res;
272 break;
273 case Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG:
274 $ids = $this->_slowBackend->getIdsNotMatchingTags($tags);
275 $res = true;
276 foreach ($ids as $id) {
277 $bool = $this->remove($id);
278 $res = $res && $bool;
280 return $res;
281 break;
282 case Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG:
283 $ids = $this->_slowBackend->getIdsMatchingAnyTags($tags);
284 $res = true;
285 foreach ($ids as $id) {
286 $bool = $this->remove($id);
287 $res = $res && $bool;
289 return $res;
290 break;
291 default:
292 Zend_Cache::throwException('Invalid mode for clean() method');
293 break;
298 * Return an array of stored cache ids
300 * @return array array of stored cache ids (string)
302 public function getIds()
304 return $this->_slowBackend->getIds();
308 * Return an array of stored tags
310 * @return array array of stored tags (string)
312 public function getTags()
314 return $this->_slowBackend->getTags();
318 * Return an array of stored cache ids which match given tags
320 * In case of multiple tags, a logical AND is made between tags
322 * @param array $tags array of tags
323 * @return array array of matching cache ids (string)
325 public function getIdsMatchingTags($tags = array())
327 return $this->_slowBackend->getIdsMatchingTags($tags);
331 * Return an array of stored cache ids which don't match given tags
333 * In case of multiple tags, a logical OR is made between tags
335 * @param array $tags array of tags
336 * @return array array of not matching cache ids (string)
338 public function getIdsNotMatchingTags($tags = array())
340 return $this->_slowBackend->getIdsNotMatchingTags($tags);
344 * Return an array of stored cache ids which match any given tags
346 * In case of multiple tags, a logical AND is made between tags
348 * @param array $tags array of tags
349 * @return array array of any matching cache ids (string)
351 public function getIdsMatchingAnyTags($tags = array())
353 return $this->_slowBackend->getIdsMatchingAnyTags($tags);
358 * Return the filling percentage of the backend storage
360 * @return int integer between 0 and 100
362 public function getFillingPercentage()
364 return $this->_slowBackend->getFillingPercentage();
368 * Return an array of metadatas for the given cache id
370 * The array must include these keys :
371 * - expire : the expire timestamp
372 * - tags : a string array of tags
373 * - mtime : timestamp of last modification time
375 * @param string $id cache id
376 * @return array array of metadatas (false if the cache id is not found)
378 public function getMetadatas($id)
380 return $this->_slowBackend->getMetadatas($id);
384 * Give (if possible) an extra lifetime to the given cache id
386 * @param string $id cache id
387 * @param int $extraLifetime
388 * @return boolean true if ok
390 public function touch($id, $extraLifetime)
392 return $this->_slowBackend->touch($id, $extraLifetime);
396 * Return an associative array of capabilities (booleans) of the backend
398 * The array must include these keys :
399 * - automatic_cleaning (is automating cleaning necessary)
400 * - tags (are tags supported)
401 * - expired_read (is it possible to read expired cache records
402 * (for doNotTestCacheValidity option for example))
403 * - priority does the backend deal with priority when saving
404 * - infinite_lifetime (is infinite lifetime can work with this backend)
405 * - get_list (is it possible to get the list of cache ids and the complete list of tags)
407 * @return array associative of with capabilities
409 public function getCapabilities()
411 $slowBackendCapabilities = $this->_slowBackend->getCapabilities();
412 return array(
413 'automatic_cleaning' => $slowBackendCapabilities['automatic_cleaning'],
414 'tags' => $slowBackendCapabilities['tags'],
415 'expired_read' => $slowBackendCapabilities['expired_read'],
416 'priority' => $slowBackendCapabilities['priority'],
417 'infinite_lifetime' => $slowBackendCapabilities['infinite_lifetime'],
418 'get_list' => $slowBackendCapabilities['get_list']
423 * Prepare a serialized array to store datas and metadatas informations
425 * @param string $data data to store
426 * @param int $lifetime original lifetime
427 * @param int $priority priority
428 * @return string serialize array to store into cache
430 private function _prepareData($data, $lifetime, $priority)
432 $lt = $lifetime;
433 if ($lt === null) {
434 $lt = 9999999999;
436 return serialize(array(
437 'data' => $data,
438 'lifetime' => $lifetime,
439 'expire' => time() + $lt,
440 'priority' => $priority
445 * Compute and return the lifetime for the fast backend
447 * @param int $lifetime original lifetime
448 * @param int $priority priority
449 * @param int $maxLifetime maximum lifetime
450 * @return int lifetime for the fast backend
452 private function _getFastLifetime($lifetime, $priority, $maxLifetime = null)
454 if ($lifetime === null) {
455 // if lifetime is null, we have an infinite lifetime
456 // we need to use arbitrary lifetimes
457 $fastLifetime = (int) (2592000 / (11 - $priority));
458 } else {
459 $fastLifetime = (int) ($lifetime / (11 - $priority));
461 if (($maxLifetime !== null) && ($maxLifetime >= 0)) {
462 if ($fastLifetime > $maxLifetime) {
463 return $maxLifetime;
466 return $fastLifetime;
470 * PUBLIC METHOD FOR UNIT TESTING ONLY !
472 * Force a cache record to expire
474 * @param string $id cache id
476 public function ___expire($id)
478 $this->_fastBackend->remove($id);
479 $this->_slowBackend->___expire($id);
482 private function _getFastFillingPercentage($mode)
485 if ($mode == 'saving') {
486 // mode saving
487 if ($this->_fastBackendFillingPercentage === null) {
488 $this->_fastBackendFillingPercentage = $this->_fastBackend->getFillingPercentage();
489 } else {
490 $rand = rand(1, $this->_options['stats_update_factor']);
491 if ($rand == 1) {
492 // we force a refresh
493 $this->_fastBackendFillingPercentage = $this->_fastBackend->getFillingPercentage();
496 } else {
497 // mode loading
498 // we compute the percentage only if it's not available in cache
499 if ($this->_fastBackendFillingPercentage === null) {
500 $this->_fastBackendFillingPercentage = $this->_fastBackend->getFillingPercentage();
503 return $this->_fastBackendFillingPercentage;