我的缓存方法:
是用ob_start()缓存的。如果没有缓存了的页面,ob_start(),然后再把buffer里的内容缓存到一个文件里。
如果有缓存而且Mtime(修改时间)比我要缓存的时间短,我就直接include这个文件(纯html)。
我需要一个缓存类。
$cache = new PartCache();$cache->start();/*
代码部分
*/$cache->end();start函数就是用来判断有没有缓存,如果没有就ob_start
end函数就看上面有没有开始缓存,如果缓存了,就ob_get_contents,然后都存到一个文件里。
但怎么也无法实现。
原因是我必须把这段代码部分用大括号包起来,才能确保有缓存文件的时候不去执行这些代码。提问:能否不用大括号,而实现部分代码缓存功能?
是用ob_start()缓存的。如果没有缓存了的页面,ob_start(),然后再把buffer里的内容缓存到一个文件里。
如果有缓存而且Mtime(修改时间)比我要缓存的时间短,我就直接include这个文件(纯html)。
我需要一个缓存类。
$cache = new PartCache();$cache->start();/*
代码部分
*/$cache->end();start函数就是用来判断有没有缓存,如果没有就ob_start
end函数就看上面有没有开始缓存,如果缓存了,就ob_get_contents,然后都存到一个文件里。
但怎么也无法实现。
原因是我必须把这段代码部分用大括号包起来,才能确保有缓存文件的时候不去执行这些代码。提问:能否不用大括号,而实现部分代码缓存功能?
如果缓存页不存在,则重新生成并保存
如果缓存页存在,则看有没有过期,如果没过期则用缓存,
如果过期就include一个出错提示,或其他页这很好判断判断你那个缓存页文件的生成时间.根据过期时间参数比较!
而且也实现了,但用法比较麻烦,如下$cache = new PartCache(); if($cache->haveCache){
$cache->print();
}else{
$cache->start(); /*
代码部分
*/ $cache->end();
}必须每次都这样用大括号{}包住。
我的问题是,能不能不加括号来实现。如我问题里的那种方法,把判断,ob_start的代码都写到 start()里面去。
echo "hello";
b();现在实现这个两个函数,不让hello打印出来
echo "hello";
}现在我不想用括号包起来也能实现不执行这个代码,比如
a();
echo "hello";
b();这个理论上是否可以实现?
$cache->print();
exit;
}
$cache->start(); /*
代码部分
*/ $cache->end();
所以理论上来说, 你必须要把代码放入ob_start[开启缓存] ob_get_contents[读取缓存内容]之间,最后ob_end.
这段代码$cache = new PartCache(); if($cache->haveCache){
$cache->print();
}else{
$cache->start(); /*
代码部分
*/ $cache->end();
}
可以改成下面这样,$cache = new PartCache(); if($cache->haveCache){
$cache->print();
}else{
$cache->start();
$cache->is_start=true;
}
/*
代码部分
*/
if($cache->is_start){
$cache->end();
}所以代码不需要放在括号中.
这个模式是缓存了输出的情况下依然会执行代码,只是存在有效缓存的情况下输出会被忽略。
我自己的缓存类则是存在缓存则直接输出并退出执行。
<?php
PartCache::start(); // 这里进行检查,如果存在缓存且缓存未超期则输出缓存,并且注册关闭函数/*
PHP code...
*/
?>
PartCache.class.php中有类似代码
class PartCache {
protected static $hasValidCache = false; public static function start($cachePath = self::CACHE_PATH) {
self::$hasValidCache = self::haveValidCache();
if (self::$hasValidCache) {
self::print();
//exit(); // 如果输出后需继续执行代码则注释以下行
}
register_shutdown_function(create_function('', 'PartCache::end();'));
ob_start();
} public static function end() {
$output = ob_get_clean();
if (!self::$hasValidCache) {
self::cacheOutput($output);
}
}
}
缓存的目的就是把一段复杂代码的结果存起来,第二次访问的时候减少数据库读取等操作。
main.phpecho $header;
include "content_part1.php";
include "content_part2.php";
echo $fotter;
content_part1.phpinclude "PartCache.class.php";// 将__FILE__作为参数以便缓存类识别调用的部分属于哪个文件
$partCache = new PartCache();
if ($partCache->cacheStart(__FILE__))
return;/*
your code...
*/$partCache->cacheEnd();
PartCache.class.phpclass PartCache {
public function cacheStart($file) {
$ret = false;
// 识别缓存文件
$this->cacheFile = $this->getCacheFilename($file);
if ($this->isValidCache($this->cacheFile)) {
$ret = true; // 返回TRUE表示已从缓存读取
$this->display($this->cacheFile);
} else {
ob_start();
}
return $ret;
} public function cacheEnd() {
file_put_contents($this->cacheFile, ob_get_clean());
}
}