1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > thinkphp6生成html TinkPHP6-tp6实现全站静态化方法

thinkphp6生成html TinkPHP6-tp6实现全站静态化方法

时间:2018-10-04 09:52:07

相关推荐

thinkphp6生成html TinkPHP6-tp6实现全站静态化方法

一,前言

模板完全静态化,也就是通过模板完全生成纯静态的网页,相比动态页面和伪静态页面更安全更利于SEO访问更快。

二,实现思路

1,根据模块/控制器_MD5(参数)动态递归创建目录

2,file_exists判断生成的静态页是否存在,是否过期,存在并且未过期则重定向到静态网页

3,不存在或者文件已过期,则file_put_contents($file,$content)函数生成静态页面

三,编码

1,基类中的生成前与生成后的方法

class Common extends BaseController

{

//静态模板生成目录

protected $staticHtmlDir = "";

//静态文件

protected $staticHtmlFile = "";

//判断是否存在静态

public function beforeBuild($param = []) {

//生成静态

$this->staticHtmlDir = "html".DS.$this->request->controller().DS;

//参数md5

$param = md5(json_encode($param));

$this->staticHtmlFile = $this->staticHtmlDir .$this->request->action() . '_' . $param .'.html';

//目录不存在,则创建

if(!file_exists($this->staticHtmlDir)){

mkdir($this->staticHtmlDir);

}

//静态文件存在,并且没有过期

if(file_exists($this->staticHtmlFile) && filectime($this->staticHtmlFile)>=time()-60*60*24*5) {

header("Location:/" . $this->staticHtmlFile);

exit();

}

}

//开始生成静态文件

public function afterBuild($html) {

if(!empty($this->staticHtmlFile) && !empty($html)) {

if(file_exists($this->staticHtmlFile)) {

\unlink($this->staticHtmlFile);

}

if(file_put_contents($this->staticHtmlFile,$html)) {

header("Location:/" . $this->staticHtmlFile);

exit();

}

}

}

}

2,控制器中的使用

public function getList($id = '')

{

//判断静态界面是否存在

$this->beforeBuild(array($id));

// do someing

$name = "测试静态化";

$html = View::fetch('/get_list',['name'=>$name]);

//生成静态界面

$this->afterBuild($html);

}

很赞哦! (0)

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。