适用:原生PHP

cache.php

tips:代码最后有适用Demo哦。

<?php
/*
* 缓存类 cache
*/
define("cacheRoot","./cache/");
define("time",0);
define("name","");
define("cacheFileExt","php");
class cache {
//缓存目录
var $cacheRoot = "./cache/";
//缓存更新时间秒数,0为不缓存
var $cacheLimitTime = 0;
//缓存文件名
var $cacheFileName = "";
//缓存扩展名
var $cacheFileExt = "php";
/*
* 构造函数,文件名、有效期
* int $time 缓存更新时间
*/
function cache($name,$time ) {
if( intval( $time ) )
$this->cacheLimitTime = $time;
//$this->cacheLimitTime = $cacheLimitTime;
$this->cacheFileName = cacheRoot.$name.".".cacheFileExt; //如:/cache/order.php
ob_start();
}
/*
* 检查缓存文件是否在设置更新时间之内
* 返回:如果在更新时间之内则返回文件内容,反之则返回失败
*/
function cacheCheck(){
if( file_exists($this->cacheFileName) ) { //1、是否存在文件,使用绝对路径 ./cache/xx
$cTime = $this->getFileCreateTime($this->cacheFileName);
if( $cTime + $this->cacheLimitTime > time() ) { //2、文件是否有效
echo file_get_contents( $this->cacheFileName ); //输出文件内容到缓存内存中
$cacheContent = ob_get_contents(); //读取缓存内存中的数据
ob_end_flush(); return $cacheContent; //输出文件缓存
exit;
}else{ //过期,删除再新建
$r = @unlink( $this->cacheFileName );
return false;
}
}
return false;
}
/*
* 读取缓存文件或者输出静态:逻辑==》1、第一次缓存文件不存在,先写缓存,立马读缓存;2、读了之后马上创建文件file
* string $staticFileName 静态文件名(含相对路径)
*/
function caching( $staticFileName = "" ){
if( $this->cacheFileName ) {
$cacheContent = ob_get_contents();
ob_end_flush();
if( $staticFileName ) {
$this->saveFile( $staticFileName, $cacheContent );
}
if( $this->cacheLimitTime )
$this->saveFile( $this->cacheFileName, $cacheContent );
}
}
/*
* 清除缓存文件
* string $fileName 指定文件名(含函数)或者all(全部)
* 返回:清除成功返回true,反之返回false
*/
function clearCache( $fileName = "all" ) {
if( $fileName != "all" ) {
$fileName = $this->cacheRoot . strtoupper(md5($fileName)).".".$this->cacheFileExt;
if( file_exists( $fileName ) ) {
return @unlink( $fileName );
}else return false;
}
if ( is_dir( $this->cacheRoot ) ) {
if ( $dir = @opendir( $this->cacheRoot ) ) {
while ( $file = @readdir( $dir ) ) {
$check = is_dir( $file );
if ( !$check )
@unlink( $this->cacheRoot . $file );
}
@closedir( $dir );
return true;
}else{
return false;
}
}else{
return false;
}
}
/*根据当前动态文件生成缓存文件名*/
function getCacheFileName() {
return $this->cacheRoot . strtoupper(md5($_SERVER["REQUEST_URI"])).".".$this->cacheFileExt;
//return $this->cacheRoot . strtoupper(md5($_SERVER["REQUEST_URI"])).".".$this->cacheFileExt;
/* $_SERVER["QUERY_STRING"] 获取查询 语句,实例中可知,获取的是?后面的值
$_SERVER["REQUEST_URI"] 获取 http://localhost 后面的值,包括/aaa/index.php?p=222&q=333
$_SERVER["SCRIPT_NAME"] 获取当前脚本的路径,如:index.php
$_SERVER["PHP_SELF"] 当前正在执行脚本的文件名
*/
}
/*
* 缓存文件建立时间
* string $fileName 缓存文件名(含相对路径)
* 返回:文件生成时间秒数,文件不存在返回0
*/
function getFileCreateTime( $fileName ) {
if( ! trim($fileName) ) return 0;
if( file_exists( $fileName ) ) {
return intval(filemtime( $fileName ));
}else return 0;
}
/*
* 保存文件
* string $fileName 文件名(含相对路径)
* string $text 文件内容
* 返回:成功返回ture,失败返回false
*/
function saveFile($fileName, $text) {
if( ! $fileName || ! $text ) return false;
if( $this->makeDir( dirname( $fileName ) ) ) {
if( $fp = fopen( $fileName, "w" ) ) {
if( @fwrite( $fp, $text ) ) {
fclose($fp);
return true;
}else {
fclose($fp);
return false;
}
}
}
return false;
}
/*
* 连续建目录
* string $dir 目录字符串
* int $mode 权限数字
* 返回:顺利创建或者全部已建返回true,其它方式返回false
*/
function makeDir( $dir, $mode = "0777" ) {
if( ! $dir ) return 0;
$dir = str_replace( "\\", "/", $dir );
$mdir = "";
foreach( explode( "/", $dir ) as $val ) {
$mdir .= $val."/";
if( $val == ".." || $val == "." || trim( $val ) == "" ) continue;
if( ! file_exists( $mdir ) ) {
if(!@mkdir( $mdir, $mode )){
return false;
}
}
}
return true;
}
}
?> <?php
//使用DEMO
// include( "cache.php" );
// $cache = new cache(fileName,7100); //实例化对象:在/cache/目录下,创建一个fileName的文件,有效期7100秒
// $cache->cacheCheck(); //检查文件1、是否存在 2、是否有效;真=返回文件内容,假=返回false
// echo date("Y-m-d H:i:s");//写入缓存
// $cache->caching(); //没有参数将上面echo的时间先读出来,在保存缓存文件;有参数,输出参数对应的缓存内容

2、核心:

缓存的使用就是:

ob_start();   //开启缓存

echo XXX;

echo YY;

$cacheContent = ob_get_contents();  //获取上面echo的内容,所有内容组合到一起,成为字符串,如上面结果【XXXYY】
ob_end_flush();     //关闭缓存

最后,saveFile($fileName);保存文件名,参照上面代码。

PHP原生:分享一个轻量级的缓存类=>cache.php的更多相关文章

  1. Android 分享一个SharedPreferences的工具类,方便保存数据

    我们平常保存一些数据,都会用到SharedPreferences,他是保存在手机里面的,具体路径是data/data/你的包名/shared_prefs/保存的文件名.xml, SharedPrefe ...

  2. 006 [翻译] Haneke(一个Swfit iOS缓存类)

    Github项目地址:https://github.com/Haneke/HanekeSwift Haneke是一个用swift写成的轻量级iOS类,以简单好用著称(design-decisions- ...

  3. 分享一个自定义的 console 类,让你不再纠结JS中的调试代码的兼容

    问题的产生 在写JS的过程中,为了调试我们常常会写很多 console.log.console.info.console.group.console.warn.console.error代码来查看JS ...

  4. 我也分享一个c# ini操作类

    刚刚看了一篇 @云菲菲 的关于基于正则的INI辅助类文章:http://www.cnblogs.com/yunfeifei/p/4081977.html,作者写的不错.还看到评论处有一个的地址:htt ...

  5. 分享一个C#的分页类

    废话不说只有代码: using System.Linq; using System.Collections.Generic; namespace CommonLibrary { public clas ...

  6. 分享一个Web弹框类

    using System; using System.Text; namespace Core { /// <summary> /// MessageBox 的摘要说明. /// < ...

  7. 分享一个MD5加密工具类

    来自:http://blog.csdn.net/zranye/article/details/8234480 Es:http://blog.csdn.net/longxibendi/article/d ...

  8. 分享一个单例模型类Singleton代码

    相关代码: ;                foreach (string key in dict.Keys)                {                    if (cou ...

  9. 分享一个php加密字符串类。

    class base64{ /** * 加密字符串 * @access static * @param string $data 字符串 * @param string $key 加密key * @r ...

随机推荐

  1. 如何重构"箭头型"代码

    本文主要起因是,一次在微博上和朋友关于嵌套好几层的if-else语句的代码重构的讨论(微博原文),在微博上大家有各式各样的问题和想法.按道理来说这些都是编程的基本功,似乎不太值得写一篇文章,不过我觉得 ...

  2. 同步FIFO的设计

    module scfifo #( , ) ( input clk, input rst_n, input wren, input rden, :] din, :] dout, output full, ...

  3. guess-number-higher-or-lower-ii

    // https://discuss.leetcode.com/topic/51353/simple-dp-solution-with-explanation // https://en.wikipe ...

  4. python部分重点底层源码剖析

    Python源码剖析—Set容器(hashtable实现) python源码剖析(内存管理和垃圾回收)

  5. Composite 组合模式 树 递归 MD

    Markdown版本笔记 我的GitHub首页 我的博客 我的微信 我的邮箱 MyAndroidBlogs baiqiantao baiqiantao bqt20094 baiqiantao@sina ...

  6. GDB调试工具总结

    程序调试的基本思想是“分析现象->假设错误原因->产生新的现象去验证假设”这样一个循环过程,根据现象如何假设错误原因,以及如何设计新的现象去验证假设,需要非常严密的分析和思考.程序中除了一 ...

  7. 关于帝国CMS迁移到新服务器上出现问题的处理办法

    在帝国CMS项目整体迁移过程中,或多或少总会出点幺蛾子,以下就常见的注意事项整理一下: 一.修改 e/config/config.php中的数据库相关配置 二.让项目文件位置具有读写权限 三.设置ph ...

  8. 菜鸟运维笔记:小记编译安装Nginx所遇到的坑

    转载请注明出处:http://blog.csdn.net/guodongxiaren/article/details/40950249 谢谢合作 前言 无论是CentOS,或是Debian/Ubunt ...

  9. COM中导出GUID

      编写COM组件的时候需要导出GUID,以下是代码示例. extern "C" const GUID CLSID_Dictionary =         { 0x54bf656 ...

  10. [AngularJS] Angular 1.3 ngMessages with ngAnimate

    Note: Can use $dirty to check whether user has intracted with the form: https://docs.angularjs.org/a ...