因为之前做一个小项目的时候,发现Kohana貌似没有静态缓存类或库,或我没找到...
于是自己写了一个,只在v2.3.4内测试过,v3请自测或改装
东西是很简单的东西,还是有改进的余地,各位看官自改吧.
<?php
/**
* @name Page Cache 页面缓存类库
* @access public
* @author 漫无目的(soyota@gmail.com)
* @version v0.1.1 alpha
* ================
* 缓存打开时,构造方法会尝试获取缓存,并输出,否则不缓存
* 使用方法:
* 1.打开 application/config/pagecache.php 进行配置
* 2.在controller构造方法内实例本类
* 3.在controller内的function内部*末尾*,增加:$this->template->render(TRUE);\n$this->pageCache->endCache();
*
* 变更为单例模式,增加单独controller缓存功能
* $this->pageCache = PageCache::Init(TRUE); //参数留空表示本controller不需要缓存
*
* 注:application/pageCache目录请设置为755权限
*
*/
ob_start();
class PageCache_Core {
protected $cache_dir; // 缓存目录
protected $lifeTime; // 缓存过期时间
protected $file; // 缓存目录和缓存文件(URI加MD5后)
public $pageCache_open; // 缓存开关
private static $_init;
private function __construct($isOpen = FALSE) {
$this->pageCache_open = ($isOpen) ? $isOpen : Kohana::config('pagecache.pageCache_open');
$this->cache_dir = Kohana::config('pagecache.pageCache_dir');
$this->lifeTime = Kohana::config('pagecache.pageCache_lifeTime') * 3600;
$this->file = $this->cache_dir . md5(urlencode(url::current()));
if($this->pageCache_open) {
$this->_start();
}
}
public static function Init($isOpen = FALSE) {
if(!self::$_init) {
self::$_init = new PageCache_Core($isOpen);
}
return self::$_init;
}
/**
* 缓存动作开始:检测缓存
* @access private
*/
private function _start() {
// 如果缓存文件存在,且存活时间未过期。**不需要更新缓存,直接输入缓存**
if(file_exists($this->file) AND (filemtime($this->file) + $this->lifeTime) > time()) {
$this->_getCache();
}
}
/**
* 将数据写入缓存数据
* @access private
*/
private function _setCache($pageData) {
if(file_put_contents($this->file, $pageData, LOCK_EX)) {
return true;
} else {
return false;
}
}
/**
* 获取缓存数据
* @access private
*/
private function _getCache() {
$data = file_get_contents($this->file);
if($data) {
echo $data;
} else {
$this->_ERROR('无法获取缓存数据');
}
ob_end_flush();
exit();
}
/**
* 本方法应该放置在代码末尾,使其设置缓存并显示
*/
public function endCache() {
if($this->pageCache_open) {
$pageData = ob_get_contents();
$this->_setCache($pageData);
ob_end_flush();
exit();
} else { // 缓存关闭
ob_end_flush();
exit();
}
}
/**
* 异常抛出
* @access private
* @param string $errMSG
* @return void
*/
private function _ERROR($errMSG) {
if(is_string($errMSG)) {
echo '发生错误:' . $errMSG;
}
}
}
?>