Home > Backend Development > PHP Tutorial > php static file cache

php static file cache

小云云
Release: 2023-03-17 11:10:01
Original
6717 people have browsed it

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);
        }
    }
}
Copy after login

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";
}
Copy after login

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);//如果没过期,输出缓存内容
}
}
Copy after login

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);
}
Copy after login

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);
Copy after login

2. Get File modification time example:

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

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template