MediaWiki  REL1_21
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                 if ( !is_int( $maxKeys ) || $maxKeys < 1 ) {
00042                         throw new MWException( __METHOD__ . " must be given an integer and >= 1" );
00043                 }
00044                 $this->maxCacheKeys = $maxKeys;
00045         }
00046 
00057         public function set( $key, $prop, $value ) {
00058                 if ( isset( $this->cache[$key] ) ) {
00059                         $this->ping( $key ); // push to top
00060                 } elseif ( count( $this->cache ) >= $this->maxCacheKeys ) {
00061                         reset( $this->cache );
00062                         $evictKey = key( $this->cache );
00063                         unset( $this->cache[$evictKey] );
00064                         unset( $this->cacheTimes[$evictKey] );
00065                 }
00066                 $this->cache[$key][$prop] = $value;
00067                 $this->cacheTimes[$key][$prop] = time();
00068         }
00069 
00078         public function has( $key, $prop, $maxAge = 0 ) {
00079                 if ( isset( $this->cache[$key][$prop] ) ) {
00080                         return ( $maxAge <= 0 || ( time() - $this->cacheTimes[$key][$prop] ) <= $maxAge );
00081                 }
00082                 return false;
00083         }
00084 
00094         public function get( $key, $prop ) {
00095                 if ( isset( $this->cache[$key][$prop] ) ) {
00096                         $this->ping( $key ); // push to top
00097                         return $this->cache[$key][$prop];
00098                 } else {
00099                         return null;
00100                 }
00101         }
00102 
00109         public function clear( $keys = null ) {
00110                 if ( $keys === null ) {
00111                         $this->cache = array();
00112                         $this->cacheTimes = array();
00113                 } else {
00114                         foreach ( (array)$keys as $key ) {
00115                                 unset( $this->cache[$key] );
00116                                 unset( $this->cacheTimes[$key] );
00117                         }
00118                 }
00119         }
00120 
00126         protected function ping( $key ) {
00127                 $item = $this->cache[$key];
00128                 unset( $this->cache[$key] );
00129                 $this->cache[$key] = $item;
00130         }
00131 }