


It took half a day to learn the knowledge of implementing LRU algorithm in PHP.
We have learned so much about PHP. Today we are learning how to implement the LRU algorithm in PHP in half a day. I don’t know. Have you completely mastered it? If not, then follow this article to continue learning
Overall design
1: Use an array to save the cache Object (Node);
2: The cache objects (Node) form a two-way linked list through nextKey and preKey;
3: Save the head and tail of the linked list;
The processing flow is as follows:
Main code
1:Node node class
/** * 缓存值保存类, * Class Node * @package app\common\model */ class Node{ private $preKey=null;//链表前一个节点 private $nextKey=null;//链表后一个节点 private $value=null;//当前的值 private $key=null;//当前key public function __construct(string $key,$value) { $this->value=$value; $this->key=$key; } public function setPreKey($preValue){ $this->preKey=$preValue; } public function setNextKey($nextValue){ $this->nextKey=$nextValue; } public function getPreKey(){ return $this->preKey; } public function getNextKey(){ return $this->nextKey; } public function getValue(){ return $this->value; } public function setValue($value){ $this->value=$value; } public function setKey(string $key){ $this->key=$key; } public function getKey(){ return $this->key; } }
2: Cache class
/** * 实现lru缓存 * Class LruCache * @package app\common\model */ class LruCache { public $cacheTable =[]; private $headNode=null; private $lastNode=null; private $cacheCount=0; private $cacheMax=100; /** * 测试输出使用 */ public function dumpAllData(){ if (!empty($this->headNode)){ $node=$this->headNode; while (!empty($node)){ echo 'key='.$node->getKey().' nextKey='.(empty($node->getNextKey())?'null':$node->getNextKey()->getKey()).' preKey='.(empty($node->getPreKey())?'null':$node->getPreKey()->getKey()).' value='.$node->getValue()."</br>"; $node=$node->getNextKey(); } } } /** * @param int $count */ public function setCacheMax(int $count){ $this->cacheMax=$count; } /** * @param string $key * @param $value * @return bool */ public function set(string $key,$value){ //设置值为null,则认为删除缓存节点 if ($value===null){ $this->del($key); return true; } //判断是否存在表中,存在则更新连表 if (!empty($this->cacheTable[$key])){ $this->updateList($key); return true; } //先判断是否要删除 $this->shiftNode(); $this->addNode($key,$value); return true; } /** * @param string $key * @return bool */ public function del(string $key){ if (!empty($this->cacheTable[$key])){ $node=&$this->cacheTable[$key]; //摘出节点 $this->jumpNode($node); //置空删除 $node->setPreKey(null); $node->setNextKey(null); unset($this->cacheTable[$key]); return true; } return false; } /** * @param string $key * @return null */ public function get(string $key){ if (!empty($this->cacheTable[$key])){ $this->updateList($key); return $this->cacheTable[$key]->getValue(); } return null; } //直接添加节点 private function addNode($key,$value){ $addNode=new Node($key,$value); if (!empty($this->headNode)){ $this->headNode->setPreKey($addNode); } $addNode->setNextKey($this->headNode); //第一次保存最后一个节点为头节点 if ($this->lastNode==null){ $this->lastNode=$addNode; } $this->headNode=$addNode; $this->cacheTable[$key]=$addNode; $this->cacheCount++; } //主动删超出的缓存 private function shiftNode(){ while ($this->cacheCount>=$this->cacheMax){ if (!empty($this->lastNode)){ if (!empty($this->lastNode->getPreKey())){ $this->lastNode->getPreKey()->setNextKey(null); } $lastKey=$this->lastNode->getKey(); unset($this->cacheTable[$lastKey]); } $this->cacheCount--; } } //更新节点链表 private function updateList($key){ //这里需要使用引用传值 $node=&$this->cacheTable[$key]; //当前结点为头结点 直接不用处理 if ($this->headNode===$node){ return true; } //摘出结点 $this->jumpNode($node); //跟头结点交换 $node->setNextKey($this->headNode); $this->headNode->setPreKey($node); $node->setPreKey(null); $this->headNode=$node; return true; } //将某个节点摘出来 private function jumpNode(Node &$node){ if (!empty($node->getPreKey())){ $node->getPreKey()->setNextKey($node->getNextKey()); } if (!empty($node->getNextKey())){ $node->getNextKey()->setPreKey($node->getPreKey()); } //如果是最后一个节点,则更新最后节点为它的前节点 if ($node->getNextKey()==null){ $this->lastNode=$node->getPreKey(); } //如果是头结点 if ($node->getPreKey()==null){ $this->headNode=$node->getNextKey(); } } }
3: Test code
public function tt(){ $cath=model("LruCache"); $cath->setCacheMax(3); $cath->set("aa","aaaaaaaaaaa"); $cath->set("bb","bbbbbbbbbbbb"); $cath->set("cc","ccccccccccccc"); $cath->get("aa"); // $cath->dumpAllData(); $cath->set("dd","ddddddddddddd"); // $cath->del("cc"); // var_dump($cath->cacheTable); $cath->dumpAllData(); exit(); }
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of It took half a day to learn the knowledge of implementing LRU algorithm in PHP.. For more information, please follow other related articles on the PHP Chinese website!

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment