Elgg  Version 1.9
LRUCache.php
Go to the documentation of this file.
1 <?php
2 
16 class Elgg_Cache_LRUCache implements ArrayAccess {
18  protected $maximumSize;
19 
25  protected $data = array();
26 
33  public function __construct($size) {
34  if (!is_int($size) || $size <= 0) {
35  throw new InvalidArgumentException();
36  }
37  $this->maximumSize = $size;
38  }
39 
47  public function get($key, $default = null) {
48  if (isset($this->data[$key])) {
49  $this->recordAccess($key);
50  return $this->data[$key];
51  } else {
52  return $default;
53  }
54  }
55 
63  public function set($key, $value) {
64  if (isset($this->data[$key])) {
65  $this->data[$key] = $value;
66  $this->recordAccess($key);
67  } else {
68  $this->data[$key] = $value;
69  if ($this->size() > $this->maximumSize) {
70  // remove least recently used element (front of array)
71  reset($this->data);
72  unset($this->data[key($this->data)]);
73  }
74  }
75  }
76 
82  public function size() {
83  return count($this->data);
84  }
85 
92  public function containsKey($key) {
93  return isset($this->data[$key]);
94  }
95 
102  public function remove($key) {
103  if (isset($this->data[$key])) {
104  $value = $this->data[$key];
105  unset($this->data[$key]);
106  return $value;
107  } else {
108  return null;
109  }
110  }
111 
117  public function clear() {
118  $this->data = array();
119  }
120 
127  protected function recordAccess($key) {
128  $value = $this->data[$key];
129  unset($this->data[$key]);
130  $this->data[$key] = $value;
131  }
132 
142  public function offsetSet($key, $value) {
143  $this->set($key, $value);
144  }
145 
154  public function offsetGet($key) {
155  return $this->get($key);
156  }
157 
166  public function offsetUnset($key) {
167  $this->remove($key);
168  }
169 
178  public function offsetExists($key) {
179  return $this->containsKey($key);
180  }
181 }
offsetGet($key)
Get the value for specified key.
Definition: LRUCache.php:154
__construct($size)
Create a LRU Cache.
Definition: LRUCache.php:33
$size
Definition: view.php:10
clear()
Clear the cache.
Definition: LRUCache.php:117
offsetSet($key, $value)
Assigns a value for the specified key.
Definition: LRUCache.php:142
$value
Definition: longtext.php:29
$default
Definition: checkbox.php:36
$key
Definition: summary.php:34
size()
Get the number of elements in the cache.
Definition: LRUCache.php:82
containsKey($key)
Does the cache contain an element with this key.
Definition: LRUCache.php:92
offsetUnset($key)
Unsets a key.
Definition: LRUCache.php:166
offsetExists($key)
Does key exist?
Definition: LRUCache.php:178
recordAccess($key)
Moves the element from current position to end of array.
Definition: LRUCache.php:127