PageRenderTime 43ms CodeModel.GetById 14ms app.highlight 20ms RepoModel.GetById 1ms app.codeStats 0ms

/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
 24/**
 25 * @see Zend_Cache_Backend_ExtendedInterface
 26 */
 27require_once 'Zend/Cache/Backend/ExtendedInterface.php';
 28
 29/**
 30 * @see Zend_Cache_Backend
 31 */
 32require_once 'Zend/Cache/Backend.php';
 33
 34
 35/**
 36 * @package    Zend_Cache
 37 * @subpackage Zend_Cache_Backend
 38 * @copyright  Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
 39 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 40 */
 41
 42class Zend_Cache_Backend_TwoLevels extends Zend_Cache_Backend implements Zend_Cache_Backend_ExtendedInterface
 43{
 44    /**
 45     * Available options
 46     *
 47     * =====> (string) slow_backend :
 48     * - Slow backend name
 49     * - Must implement the Zend_Cache_Backend_ExtendedInterface
 50     * - Should provide a big storage
 51     *
 52     * =====> (string) fast_backend :
 53     * - Flow backend name
 54     * - Must implement the Zend_Cache_Backend_ExtendedInterface
 55     * - Must be much faster than slow_backend
 56     *
 57     * =====> (array) slow_backend_options :
 58     * - Slow backend options (see corresponding backend)
 59     *
 60     * =====> (array) fast_backend_options :
 61     * - Fast backend options (see corresponding backend)
 62     *
 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
 68     *
 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
 74     *
 75     * =====> (boolean) auto_refresh_fast_cache
 76     * - If true, auto refresh the fast cache when a cache record is hit
 77     *
 78     * @var array available options
 79     */
 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
 91    );
 92
 93    /**
 94     * Slow Backend
 95     *
 96     * @var Zend_Cache_Backend
 97     */
 98    protected $_slowBackend;
 99
100    /**
101     * Fast Backend
102     *
103     * @var Zend_Cache_Backend
104     */
105    protected $_fastBackend;
106
107    /**
108     * Cache for the fast backend filling percentage
109     *
110     * @var int
111     */
112    protected $_fastBackendFillingPercentage = null;
113
114    /**
115     * Constructor
116     *
117     * @param  array $options Associative array of options
118     * @throws Zend_Cache_Exception
119     * @return void
120     */
121    public function __construct(array $options = array())
122    {
123        parent::__construct($options);
124        if ($this->_options['slow_backend'] === null) {
125            Zend_Cache::throwException('slow_backend option has to set');
126        }
127        if ($this->_options['fast_backend'] === null) {
128            Zend_Cache::throwException('fast_backend option has to set');
129        }
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');
134        }
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');
137        }
138        $this->_slowBackend->setDirectives($this->_directives);
139        $this->_fastBackend->setDirectives($this->_directives);
140    }
141
142    /**
143     * Test if a cache is available or not (for the given id)
144     *
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
147     */
148    public function test($id)
149    {
150        $fastTest = $this->_fastBackend->test($id);
151        if ($fastTest) {
152            return $fastTest;
153        } else {
154            return $this->_slowBackend->test($id);
155        }
156    }
157
158    /**
159     * Save some string datas into a cache record
160     *
161     * Note : $data is always "string" (serialization is done by the
162     * core not by the backend)
163     *
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
170     */
171    public function save($data, $id, $tags = array(), $specificLifetime = false, $priority = 8)
172    {
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);
180        }
181        $boolSlow = $this->_slowBackend->save($preparedData, $id, $tags, $lifetime);
182        return ($boolFast && $boolSlow);
183    }
184
185    /**
186     * Test if a cache is available for the given id and (if yes) return it (false else)
187     *
188     * Note : return value is always "string" (unserialization is done by the core not by the backend)
189     *
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
193     */
194    public function load($id, $doNotTestCacheValidity = false)
195    {
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;
202            }
203        }
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'];
210            }
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);
218            }
219        }
220        return $array['data'];
221    }
222
223    /**
224     * Remove a cache record
225     *
226     * @param  string $id Cache id
227     * @return boolean True if no problem
228     */
229    public function remove($id)
230    {
231        $boolFast = $this->_fastBackend->remove($id);
232        $boolSlow = $this->_slowBackend->remove($id);
233        return $boolFast && $boolSlow;
234    }
235
236    /**
237     * Clean some cache records
238     *
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)
248     *
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
253     */
254    public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array())
255    {
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;
270                }
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;
279                }
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;
288                }
289                return $res;
290                break;
291            default:
292                Zend_Cache::throwException('Invalid mode for clean() method');
293                break;
294        }
295    }
296
297    /**
298     * Return an array of stored cache ids
299     *
300     * @return array array of stored cache ids (string)
301     */
302    public function getIds()
303    {
304        return $this->_slowBackend->getIds();
305    }
306
307    /**
308     * Return an array of stored tags
309     *
310     * @return array array of stored tags (string)
311     */
312    public function getTags()
313    {
314        return $this->_slowBackend->getTags();
315    }
316
317    /**
318     * Return an array of stored cache ids which match given tags
319     *
320     * In case of multiple tags, a logical AND is made between tags
321     *
322     * @param array $tags array of tags
323     * @return array array of matching cache ids (string)
324     */
325    public function getIdsMatchingTags($tags = array())
326    {
327        return $this->_slowBackend->getIdsMatchingTags($tags);
328    }
329
330    /**
331     * Return an array of stored cache ids which don't match given tags
332     *
333     * In case of multiple tags, a logical OR is made between tags
334     *
335     * @param array $tags array of tags
336     * @return array array of not matching cache ids (string)
337     */
338    public function getIdsNotMatchingTags($tags = array())
339    {
340        return $this->_slowBackend->getIdsNotMatchingTags($tags);
341    }
342
343    /**
344     * Return an array of stored cache ids which match any given tags
345     *
346     * In case of multiple tags, a logical AND is made between tags
347     *
348     * @param array $tags array of tags
349     * @return array array of any matching cache ids (string)
350     */
351    public function getIdsMatchingAnyTags($tags = array())
352    {
353        return $this->_slowBackend->getIdsMatchingAnyTags($tags);
354    }
355
356
357    /**
358     * Return the filling percentage of the backend storage
359     *
360     * @return int integer between 0 and 100
361     */
362    public function getFillingPercentage()
363    {
364        return $this->_slowBackend->getFillingPercentage();
365    }
366
367    /**
368     * Return an array of metadatas for the given cache id
369     *
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
374     *
375     * @param string $id cache id
376     * @return array array of metadatas (false if the cache id is not found)
377     */
378    public function getMetadatas($id)
379    {
380        return $this->_slowBackend->getMetadatas($id);
381    }
382
383    /**
384     * Give (if possible) an extra lifetime to the given cache id
385     *
386     * @param string $id cache id
387     * @param int $extraLifetime
388     * @return boolean true if ok
389     */
390    public function touch($id, $extraLifetime)
391    {
392        return $this->_slowBackend->touch($id, $extraLifetime);
393    }
394
395    /**
396     * Return an associative array of capabilities (booleans) of the backend
397     *
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)
406     *
407     * @return array associative of with capabilities
408     */
409    public function getCapabilities()
410    {
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']
419        );
420    }
421
422    /**
423     * Prepare a serialized array to store datas and metadatas informations
424     *
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
429     */
430    private function _prepareData($data, $lifetime, $priority)
431    {
432        $lt = $lifetime;
433        if ($lt === null) {
434            $lt = 9999999999;
435        }
436        return serialize(array(
437            'data' => $data,
438            'lifetime' => $lifetime,
439            'expire' => time() + $lt,
440            'priority' => $priority
441        ));
442    }
443
444    /**
445     * Compute and return the lifetime for the fast backend
446     *
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
451     */
452    private function _getFastLifetime($lifetime, $priority, $maxLifetime = null)
453    {
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));
460        }
461        if (($maxLifetime !== null) && ($maxLifetime >= 0)) {
462            if ($fastLifetime > $maxLifetime) {
463                return $maxLifetime;
464            }
465        }
466        return $fastLifetime;
467    }
468
469    /**
470     * PUBLIC METHOD FOR UNIT TESTING ONLY !
471     *
472     * Force a cache record to expire
473     *
474     * @param string $id cache id
475     */
476    public function ___expire($id)
477    {
478        $this->_fastBackend->remove($id);
479        $this->_slowBackend->___expire($id);
480    }
481
482    private function _getFastFillingPercentage($mode)
483    {
484
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();
494                }
495            }
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();
501            }
502        }
503        return $this->_fastBackendFillingPercentage;
504    }
505
506}