MediaWiki  REL1_24
MapCacheLRU.php
Go to the documentation of this file.
00001 <?php
00033 class MapCacheLRU {
00035     protected $cache = array(); // (key => value)
00036 
00037     protected $maxCacheKeys; // integer; max entries
00038 
00043     public function __construct( $maxKeys ) {
00044         if ( !is_int( $maxKeys ) || $maxKeys < 1 ) {
00045             throw new MWException( __METHOD__ . " must be given an integer and >= 1" );
00046         }
00047         $this->maxCacheKeys = $maxKeys;
00048     }
00049 
00059     public function set( $key, $value ) {
00060         if ( array_key_exists( $key, $this->cache ) ) {
00061             $this->ping( $key ); // push to top
00062         } elseif ( count( $this->cache ) >= $this->maxCacheKeys ) {
00063             reset( $this->cache );
00064             $evictKey = key( $this->cache );
00065             unset( $this->cache[$evictKey] );
00066         }
00067         $this->cache[$key] = $value;
00068     }
00069 
00076     public function has( $key ) {
00077         return array_key_exists( $key, $this->cache );
00078     }
00079 
00088     public function get( $key ) {
00089         if ( array_key_exists( $key, $this->cache ) ) {
00090             $this->ping( $key ); // push to top
00091             return $this->cache[$key];
00092         } else {
00093             return null;
00094         }
00095     }
00096 
00103     public function clear( $keys = null ) {
00104         if ( $keys === null ) {
00105             $this->cache = array();
00106         } else {
00107             foreach ( (array)$keys as $key ) {
00108                 unset( $this->cache[$key] );
00109             }
00110         }
00111     }
00112 
00118     protected function ping( $key ) {
00119         $item = $this->cache[$key];
00120         unset( $this->cache[$key] );
00121         $this->cache[$key] = $item;
00122     }
00123 }