MediaWiki  REL1_24
ProcessCacheLRU.php
Go to the documentation of this file.
00001 <?php
00028 class ProcessCacheLRU {
00030     protected $cache = array(); // (key => prop => value)
00032     protected $cacheTimes = array(); // (key => prop => UNIX timestamp)
00033 
00034     protected $maxCacheKeys; // integer; max entries
00035 
00040     public function __construct( $maxKeys ) {
00041         $this->resize( $maxKeys );
00042     }
00043 
00054     public function set( $key, $prop, $value ) {
00055         if ( isset( $this->cache[$key] ) ) {
00056             $this->ping( $key ); // push to top
00057         } elseif ( count( $this->cache ) >= $this->maxCacheKeys ) {
00058             reset( $this->cache );
00059             $evictKey = key( $this->cache );
00060             unset( $this->cache[$evictKey] );
00061             unset( $this->cacheTimes[$evictKey] );
00062         }
00063         $this->cache[$key][$prop] = $value;
00064         $this->cacheTimes[$key][$prop] = time();
00065     }
00066 
00075     public function has( $key, $prop, $maxAge = 0 ) {
00076         if ( isset( $this->cache[$key][$prop] ) ) {
00077             return ( $maxAge <= 0 || ( time() - $this->cacheTimes[$key][$prop] ) <= $maxAge );
00078         }
00079 
00080         return false;
00081     }
00082 
00092     public function get( $key, $prop ) {
00093         if ( isset( $this->cache[$key][$prop] ) ) {
00094             $this->ping( $key ); // push to top
00095             return $this->cache[$key][$prop];
00096         } else {
00097             return null;
00098         }
00099     }
00100 
00107     public function clear( $keys = null ) {
00108         if ( $keys === null ) {
00109             $this->cache = array();
00110             $this->cacheTimes = array();
00111         } else {
00112             foreach ( (array)$keys as $key ) {
00113                 unset( $this->cache[$key] );
00114                 unset( $this->cacheTimes[$key] );
00115             }
00116         }
00117     }
00118 
00125     public function resize( $maxKeys ) {
00126         if ( !is_int( $maxKeys ) || $maxKeys < 1 ) {
00127             throw new UnexpectedValueException( __METHOD__ . " must be given an integer >= 1" );
00128         }
00129         $this->maxCacheKeys = $maxKeys;
00130         while ( count( $this->cache ) > $this->maxCacheKeys ) {
00131             reset( $this->cache );
00132             $evictKey = key( $this->cache );
00133             unset( $this->cache[$evictKey] );
00134             unset( $this->cacheTimes[$evictKey] );
00135         }
00136     }
00137 
00143     protected function ping( $key ) {
00144         $item = $this->cache[$key];
00145         unset( $this->cache[$key] );
00146         $this->cache[$key] = $item;
00147     }
00148 }