Home Backend Development PHP Tutorial php static file cache

php static file cache

Nov 11, 2017 pm 01:27 PM
php document cache

PHP file caching is mainly used to reduce the pressure on the database server. The static caching of PHP files mentioned here refers to static, directly generating text files such as HTML or XML, and regenerating them when there are updates, which is suitable for applications that do not change much. page.

1. Static file cache
2.Memcache, redis cache
Static cache: Use php to assemble the data, and then write the data into the file.
staticcache.php

<?php
class File{
    private $_dir;//定义一个默认的路径
    const EXT = &#39;.txt&#39;;//定义一个文件名后缀的常量
    public function __construct(){
        $this->_dir = dirname(__FILE__).&#39;/files/&#39;;//获取文件的当前目录,再放到该目录下的files文件夹中,然后赋给$_dir
    }
    //把生成/获取/删除缓存这三个操作封装在cacheData方法中
    public function cacheData($key,$value = &#39;&#39;,$path = &#39;&#39;){
        $filename = $this->_dir.$path.$key.self::EXT;//拼装成一个文件:默认目录、路径、文件名、文件名后缀
        //将value值写入缓存
        if($value !== &#39;&#39;){
        //删除缓存
            if (is_null($value)){
                return @unlink($filename);//unlink删除文件,@忽略警告
            }
            $dir = dirname($filename);
            if(!is_dir($dir)){//如果目录不存在就创建目录,首先要获取这个目录
            mkdir($dir,0777);
        }
        return file_put_contents($filename, json_encode($value));}
        //获取缓存
        if(!is_file($filename)){
        return FALSE;
        }else{
            return json_decode(file_get_contents($filename),true);
        }
    }
}

test.php

<?php
require_once(&#39;./staticcache.php&#39;);
$data = array(
&#39;id&#39; => 1,
&#39;name&#39; => &#39;panda&#39;,
&#39;number&#39; => array(1,7,8)
);
$file = new File();
//获取缓存
if($file->cacheData(&#39;index_cache&#39;)){
    var_dump($file->cacheData(&#39;index_cache&#39;));exit;
    echo "success";
}else{
    echo "error";
}

After setting the static cache time optimization:
cachetime.php

<?php
class File{
    private $_dir;//定义一个默认的路径
    const EXT = &#39;.txt&#39;;//定义一个文件名后缀的常量
    public function __construct(){
        $this->_dir = dirname(__FILE__).&#39;/files/&#39;;//获取文件的当前目录,再放到该目录下的files文件夹中,然后赋给$_dir
    }
    //把生成/获取/删除缓存这三个操作封装在cacheData方法中
    public function cacheData($key,$value = &#39;&#39;,$cacheTime = 0){//不传cacheTime永久有效
        $filename = $this->_dir.$key.self::EXT;//拼装成一个文件:默认目录、路径、文件名、文件名后缀
        //将value值写入缓存
        if($value !== &#39;&#39;){
//删除缓存
if (is_null($value)){
return @unlink($filename);//unlink删除文件,@忽略警告
}
$dir = dirname($filename);
if(!is_dir($dir)){//如果目录不存在就创建目录,首先要获取这个目录
mkdir($dir,0777);
}
$cacheTime = sprintf(&#39;%011d&#39;,$cacheTime)//规定缓存时间格式,不足11位,则前面补0,方便获取时截取
return file_put_contents($filename, $cacheTime.json_encode($value));//缓存时间与数据拼接
}
        //获取缓存
if(!is_file($filename)){
return FALSE;
}
$contents = file_get_contents($filename);
$cacheTime = (int)substr($contents,0,11);
$value = substr($contents,11);
if($cacheTime !=0 && ($cacheTime + fileatime($filename)<time())){//判断是否过期
unlink($filename);//缓存失效删除文件
return FALSE;
}
return json_decode($value,true);//如果没过期,输出缓存内容
}
}

Cache method to develop homepage interface

<?php
require_once(&#39;./jsonxml.php&#39;);
require_once(&#39;./db.php&#39;);
require_once(&#39;./cachetime.php&#39;);
$page = isset($_GET[&#39;page&#39;]) ? $_GET[&#39;page&#39;] : 1;
$pageSize = isset($_GET[&#39;pagesize&#39;]) ? $_GET[&#39;pagesize&#39;] : 6;
if(!is_numeric($page)||!is_numeric($pageSize)){
return Response::show(401,&#39;数据不合法&#39;);
}
$offset = ($page - 1) * $pageSize;
$sql = "select * from video where status = 1 order by orderby desc limit ".$offset.",".$pageSize;
//4-4 读取缓存方式开发首页接口
$cache = new File();$videos = array();
if(!$videos = $cache->cacheData(&#39;index_yjp_cache&#39;.$page.&#39;-&#39;.$pageSize)){
echo 1;exit;//如果缓存失效输出1
try{
$connect = Db::getInstance()->connect();
}catch(Exception $e){
return Response::show(403,&#39;数据库链接失败&#39;);
}
$result = mysql_query($sql,$connect);
$videos = array();
while ($video = mysql_fetch_assoc($result)){
$videos[] = $video;
}
if($videos){
$cache->cacheData(&#39;index_yjp_cache&#39;.$page.&#39;-&#39;.$pageSize,$videos,1200);
}
}
if($videos){
return Response::show(200,&#39;首页数据获取成功&#39;,$videos);
}else{
return Response::show(400,&#39;失败&#39;,$videos);
}

Note: File cache should pay attention to the expiration time of the file
1. Get the file creation time example:

$ctime=filectime("chinawinxp.txt");
echo "创建时间:".date("Y-m-d H:i:s",$ctime);

2. Get File modification time example:

$mtime=filemtime("chinawinxp.txt");
echo "修改时间:".date("Y-m-d H:i:s",$mtime);

fileatime() function returns the last access time of the specified file

2.memcache and redis cache
Enable service; connection port, cache server ; PHP operation PHP operation redis, mencache conditions:
1) Install phpredis extension/mencache extension
2) PHP connect redis service connet(127.0.0.1,6379);
Connect mencache service connet('memcache_host' ,11211);
3) set set cache
4) get get cache
Set cache time: set key time (time) value

PHP cache includes PHP compilation cache and There are two types of PHP data caching. PHP is an interpreted language that compiles and runs at the same time. The advantage of this operating mode is that program modification is very convenient, but the operating efficiency is very low. The PHP compilation cache has been improved to deal with this situation, so that the PHP language can cache the compilation results of the program as long as it is run once. In this way, every subsequent run does not need to be compiled again, which greatly improves the running speed of PHP.

Related recommendations:

implementation code for php static cache to improve website access speed

ThinkPHP static cache update problem

thinkphp static cache usage analysis, thinkphp static cache_PHP tutorial

The above is the detailed content of php static file cache. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Commenting Out Code in PHP Commenting Out Code in PHP Jul 18, 2025 am 04:57 AM

There are three common methods for PHP comment code: 1. Use // or # to block one line of code, and it is recommended to use //; 2. Use /.../ to wrap code blocks with multiple lines, which cannot be nested but can be crossed; 3. Combination skills comments such as using /if(){}/ to control logic blocks, or to improve efficiency with editor shortcut keys, you should pay attention to closing symbols and avoid nesting when using them.

Tips for Writing PHP Comments Tips for Writing PHP Comments Jul 18, 2025 am 04:51 AM

The key to writing PHP comments is to clarify the purpose and specifications. Comments should explain "why" rather than "what was done", avoiding redundancy or too simplicity. 1. Use a unified format, such as docblock (/*/) for class and method descriptions to improve readability and tool compatibility; 2. Emphasize the reasons behind the logic, such as why JS jumps need to be output manually; 3. Add an overview description before complex code, describe the process in steps, and help understand the overall idea; 4. Use TODO and FIXME rationally to mark to-do items and problems to facilitate subsequent tracking and collaboration. Good annotations can reduce communication costs and improve code maintenance efficiency.

Quick PHP Installation Tutorial Quick PHP Installation Tutorial Jul 18, 2025 am 04:52 AM

ToinstallPHPquickly,useXAMPPonWindowsorHomebrewonmacOS.1.OnWindows,downloadandinstallXAMPP,selectcomponents,startApache,andplacefilesinhtdocs.2.Alternatively,manuallyinstallPHPfromphp.netandsetupaserverlikeApache.3.OnmacOS,installHomebrew,thenrun'bre

Learning PHP: A Beginner's Guide Learning PHP: A Beginner's Guide Jul 18, 2025 am 04:54 AM

TolearnPHPeffectively,startbysettingupalocalserverenvironmentusingtoolslikeXAMPPandacodeeditorlikeVSCode.1)InstallXAMPPforApache,MySQL,andPHP.2)Useacodeeditorforsyntaxsupport.3)TestyoursetupwithasimplePHPfile.Next,learnPHPbasicsincludingvariables,ech

Improving Readability with Comments Improving Readability with Comments Jul 18, 2025 am 04:46 AM

The key to writing good comments is to explain "why" rather than just "what was done" to improve the readability of the code. 1. Comments should explain logical reasons, such as considerations behind value selection or processing; 2. Use paragraph annotations for complex logic to summarize the overall idea of functions or algorithms; 3. Regularly maintain comments to ensure consistency with the code, avoid misleading, and delete outdated content if necessary; 4. Synchronously check comments when reviewing the code, and record public logic through documents to reduce the burden of code comments.

Writing Effective PHP Comments Writing Effective PHP Comments Jul 18, 2025 am 04:44 AM

Comments cannot be careless because they want to explain the reasons for the existence of the code rather than the functions, such as compatibility with old interfaces or third-party restrictions, otherwise people who read the code can only rely on guessing. The areas that must be commented include complex conditional judgments, special error handling logic, and temporary bypass restrictions. A more practical way to write comments is to select single-line comments or block comments based on the scene. Use document block comments to explain parameters and return values at the beginning of functions, classes, and files, and keep comments updated. For complex logic, you can add a line to the previous one to summarize the overall intention. At the same time, do not use comments to seal code, but use version control tools.

Mastering PHP Block Comments Mastering PHP Block Comments Jul 18, 2025 am 04:35 AM

PHPblockcommentsareusefulforwritingmulti-lineexplanations,temporarilydisablingcode,andgeneratingdocumentation.Theyshouldnotbenestedorleftunclosed.BlockcommentshelpindocumentingfunctionswithPHPDoc,whichtoolslikePhpStormuseforauto-completionanderrorche

PHP Development Environment Setup PHP Development Environment Setup Jul 18, 2025 am 04:55 AM

The first step is to select the integrated environment package XAMPP or MAMP to build a local server; the second step is to select the appropriate PHP version according to the project needs and configure multiple version switching; the third step is to select VSCode or PhpStorm as the editor and debug with Xdebug; in addition, you need to install Composer, PHP_CodeSniffer, PHPUnit and other tools to assist in development.

See all articles