3 * Per-process memory cache for storing items.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
25 * Handles a simple LRU key/value map with a maximum number of entries
27 * Use ProcessCacheLRU if hierarchical purging is needed or objects can become stale
29 * @see ProcessCacheLRU
34 protected $cache = array(); // (key => value)
36 protected $maxCacheKeys; // integer; max entries
39 * @param $maxKeys integer Maximum number of entries allowed (min 1).
40 * @throws MWException When $maxCacheKeys is not an int or =< 0.
42 public function __construct( $maxKeys ) {
43 if ( !is_int( $maxKeys ) ||
$maxKeys < 1 ) {
44 throw new MWException( __METHOD__
. " must be given an integer and >= 1" );
46 $this->maxCacheKeys
= $maxKeys;
50 * Set a key/value pair.
51 * This will prune the cache if it gets too large based on LRU.
52 * If the item is already set, it will be pushed to the top of the cache.
58 public function set( $key, $value ) {
59 if ( isset( $this->cache
[$key] ) ) {
60 $this->ping( $key ); // push to top
61 } elseif ( count( $this->cache
) >= $this->maxCacheKeys
) {
62 reset( $this->cache
);
63 $evictKey = key( $this->cache
);
64 unset( $this->cache
[$evictKey] );
66 $this->cache
[$key] = $value;
70 * Get the value for a key.
71 * This returns null if the key is not set.
72 * If the item is already set, it will be pushed to the top of the cache.
78 public function get( $key ) {
79 if ( isset( $this->cache
[$key] ) ) {
80 $this->ping( $key ); // push to top
81 return $this->cache
[$key];
88 * Clear one or several cache entries, or all cache entries
90 * @param $keys string|Array
93 public function clear( $keys = null ) {
94 if ( $keys === null ) {
95 $this->cache
= array();
97 foreach ( (array)$keys as $key ) {
98 unset( $this->cache
[$key] );
104 * Push an entry to the top of the cache
108 protected function ping( $key ) {
109 $item = $this->cache
[$key];
110 unset( $this->cache
[$key] );
111 $this->cache
[$key] = $item;