This article describes the method of PHP to implement cache based on file storage. Share it for your reference. The details are as follows:
When some database data records are large but the server is limited, a MySQL query may take hundreds of milliseconds. A simple page usually has more than a dozen queries. At this time, it will take several seconds to load a page. If the concurrency volume is high, the server will basically be paralyzed, causing a page to not be loaded for a long time. At this time, we can use file cache to relieve the pressure of MySQL. Here is an example of usage.
<?php //Page business logic processing to obtain results$objPage = new Page_IndexModel($arrParams); //A series of business logic is placed in objPage, and the process method is called to obtain the result set$arrResult = $objPage->process(); //After obtaining the result, smarty assignment$smarty->assign($arrResult); //Output template$smarty->display(); ?>
Now we use file cache to skip the Page business processing step
<?php $cachFile = './'; //The cached file exists and the time does not exceed one hour, then the cached result set is directly used and no MySQL query is being conducted.if(file_exists($cacheFile) && time()-filemtime($cachFile) < 3600) { //Use the cached results $arrResult = include($cachFile); } else { $objPage = new Page_IndexModel($arrParams); $arrResult = $objPage->process(); $strContent = "<?php \n return ".var_export($arrResult, true)."\n;"; //Cach the result set file_put_contents($cachFile, $strContent); } //After obtaining the result, smarty assignment$smarty->assign($arrResult); //Output template$smarty->display();
I hope this article will be helpful to everyone's PHP programming.