实例Php lru,PHPLRU(最近最少使用)缓存实例教程
在这个实例中,我们将使用PHP实现一个简单的LRU(最近最少使用)缓存。LRU缓存是一种常用的缓存策略,它基于这样的原则:如果一个数据最近被访问过,那么它很可能在未来也会被访问。下面是具体的实现步骤和代码。
步骤1:定义LRUCache类
我们需要定义一个LRUCache类,它将包含一个固定大小的缓存和两个方法:get和put。

```php
class LRUCache {
private $cache;
private $capacity;
public function __construct($capacity) {
$this->cache = [];
$this->capacity = $capacity;
}
public function get($key) {
if (!array_key_exists($key, $this->cache)) {
return null;
}
// 将访问过的key移动到数组开头
$value = array_shift($this->cache);
$this->cache = array_merge([$key => $value], $this->cache);
return $value;
}
public function put($key, $value) {
if (array_key_exists($key, $this->cache)) {
// 如果key已经存在,移动到数组开头
$this->cache = array_merge(array_diff_key($this->cache, [$key => null]), [$key => $value]);
} elseif (count($this->cache) >= $this->capacity) {
// 如果缓存已满,移除最后一个元素
array_pop($this->cache);
}
$this->cache = array_merge([$key => $value], $this->cache);
}
}
```
步骤2:使用LRUCache类
接下来,我们将使用LRUCache类来实现一个简单的缓存示例。
```php
$cache = new LRUCache(2);
// 添加数据
$cache->put(1, 'a');
$cache->put(2, 'b');
echo $cache->get(1) . "