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