静态 tp5 真实静态 ThinkPHP tp
框架外静态生成学习
1、开启缓存 ob_start
ob_start();
复制代码
2、获取内容
echo 12355554;
复制代码
3、写入文件并关闭缓存
file_put_contents("./zz.html",ob_get_clean());
复制代码
静态文件触发方式,
1、设置缓存时间,超过时间的重新生成(判断文件是否存在和最后修改时间如:if(is_file(路径)&&-filemtime(路径)))
2、手动后台触发
3、内容自动定时扫描(定时任务)
tp5视图类目录 /thinkphp/library/think/View.php
参考网站:https://my.oschina.net/u/2456768/blog/3115472
1 . 根据模块控制器自动递归创建目录。
-
file_exists判断生成的静态页是否存在
-
或判断过期与否,存在重定向到静态网页
-
file_put_contents( content)函数生成页面。
下面代码 -
目录的创建
/*
- 递归创建目录
- @param string $dir 文件目录路径
- @return boolean 创建结果
- **/
function mkdirs(KaTeX parse error: Expected '}', got 'EOF' at end of input: … { if(!is_dir(dir))
{
if(!mkdirs(dirname( dir,0777)){
return false;
}
}
return true;
}
复制代码
2. 在基类中初始化需创建的目录
protected $staticHtmlDir = “”; //静态模板生成目录
protected $staticHtmlFile = “”; //静态文件
protected function _initialize() {
parent::_initialize();
this->request->controller().DS;
}
复制代码
3. 基类中的生成前与生成后的方法。
//判断是否存在静态
public function beforeBuild(KaTeX parse error: Expected '}', got 'EOF' at end of input: …生成静态 //baseDir = “html”.DS.
param)) {
param);
}
$this->staticHtmlFile =
this->request->action().(
param:’’).’.html’;
//创建目录mkdirs()
if(mkdirs(KaTeX parse error: Expected '}', got 'EOF' at end of input: …if(file_exists(this->staticHtmlFile) && filectime($this->staticHtmlFile)>=time()-606024*5) {
//
//
this->staticHtmlFile);
}
}
}
复制代码
//开始生成静态文件
public function afterBuild(KaTeX parse error: Expected '}', got 'EOF' at end of input: … if(!empty(this->staticHtmlFile) && !empty(KaTeX parse error: Expected '}', got 'EOF' at end of input: …if(file_exists(this->staticHtmlFile)) {
//
unlinnk(KaTeX parse error: Expected 'EOF', got '}' at position 36: …); }̲ //…this->staticHtmlFile,$html)) {
//
this->staticHtmlFile);
}
}
}
复制代码
4. 视图控制器中的使用。
//对静态模板进行判断
$this->beforeBuild(array($cid,$page));
复制代码
替换渲染页代码成下面代码
//获取html
this->fetch();
//生成静态
html)