经典实用的PHP缓存类库
2022-05-31Redis
php缓存技术是在开发过程中非常的常用和重要,缓存技术可减轻服务器负载、降低网络拥塞、增强www可扩展性,其基本思想是利用客户访问的时间局部性,将客户访问过的内容在Cache中存放一个副本,当该内容下次被访问时,不必连接到驻留网站,而是由Cache中保留的副本提供。
php缓存技术是在开发过程中非常的常用和重要,缓存技术可减轻服务器负载、降低网络拥塞、增强www可扩展性,其基本思想是利用客户访问的时间局部性,将客户访问过的内容在Cache中存放一个副本,当该内容下次被访问时,不必连接到驻留网站,而是由Cache中保留的副本提供。
一、PHP缓存类库代码
<?php
class Cache{
// 缓存的文件路径
private $basePth;
/**
* Cache constructor.
* @param string $basePth 文件路径
*/
public function Cache($basePth='cache')
{
$this->basePth = $basePth;
}
/**
* @param $key 键值
* @param $con 存入的内容
* @param $ext 后缀
* @return int
*/
public function setCache($key,$con,$ext='.php')
{
$path = $this->getPath($key,$ext);
return file_put_contents($path,$con);
}
//参数 time 表示cache的存活期,单位 秒,默认无限期
/**
* @param $key 键值
* @param int $time 时间
* @return bool|string
*/
public function getCache($key,$ext='.php',$time=0)
{
$path = $this->getPath($key,$ext);
if(!is_file($path))return false;
if($time&&filemtime($path)+$time<time())
{ //过期删除
unlink($path);
return false;
}
return file_get_contents($path);
}
/**
* @param $key 键值
* @param $ext 缓存文件后缀
* @return string
* @desc 得到路径
*/
private function getPath($key,$ext='.php')
{
$key = md5($key);
$keyDir = $this->basePth.'/'.substr($key,0,1).'/'.substr($key,1,1).'/';
$this->mkdirs($keyDir);
return $keyDir.$key.$ext;
}
//创造指定的多级路径
//参数 要创建的路径 文件夹的权限
//返回值 布尔值
private function mkdirs($dir, $mode = 0755)
{
if (is_dir($dir) || @mkdir($dir,$mode)) return true;
if (!$this->mkdirs(dirname($dir),$mode)) return false;
return @mkdir($dir,$mode);
}
}
二、设置缓存
<?php
$cache = new Cache();
// 把百度的网页存入变量 $html_str
$html_str = file_get_contents('https://www.baidu.com/');
// 把抓取的百度变量存入键值 baidu ,缓存的文件后缀为 html
echo $cache->setCache('baidu',$html_str, '.html').'<br/>';

三、读取缓存
<?php
// 读取存入的百度数据
echo $cache->getCache('baidu','.html');
四、直接读取缓存的文件

很赞哦! ()
