在ci中有个页面缓存,控制器中使用$this->output->cache(n);即可缓存当前页面地址的整个html,针对不常变化的页面非常有用。得道网也有很多页面是不常变化的,可以对整个页面做缓存,实现原理同codeigniter。 首先是在钩子函数routerShutdown中做拦截处理,
在ci中有个页面缓存,控制器中使用$this->output->cache(n);即可缓存当前页面地址的整个html,针对不常变化的页面非常有用。得道网也有很多页面是不常变化的,可以对整个页面做缓存,实现原理同codeigniter。
首先是在钩子函数routerShutdown中做拦截处理,获取当前URI,以当前URI做KEY,判断是否存在该KEY的缓存,若存在则停止解析,直接输出页面。
public function routerShutdown(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response)
{
$Service_Cache = new Service_Cache();
if($content = $Service_Cache->getUrlCache($request->getRequestUri())) {
echo $content;exit;
}
}
然后就是写缓存的动作,可以在特定的控制器或公用的模版渲染函数中处理。这里直接用了传参的方式接收参数,也可以类似CI Output类中的cache函数处理。
public function render($template, $data = array(), $return = false, $is_cache = false)
{
$template = $this->_twig->loadTemplate ($this->getTemplateName($template));
$data = array_merge($this->_data, is_array($data) ? $data : array());
$content = $template->render ( $data );
if ($return === TRUE) {
return $content;
}
if($is_cache == true) {
$Service_Cache = new Service_Cache();
$Service_Cache->setUrlCache(Yaf_Dispatcher::getInstance()->getRequest()->getRequestUri(), $content);
}
echo $content;
}
最后就是哪些页面需要使用缓存,可以默认设置$is_cache为true,也可以针对特定控制器处理,得道网对首页和Bible页面做了处理,调用如下。
class BibleController extends Yaf_Controller_Abstract
{
public function chapterAction()
{
//...
$this->getView()->render('tpl/bible_chapter', array(
'bible' => $bible,
), false, true);
}
}
刷新验证,可以感受到一点点效果。
原文地址:Yaf实现页面缓存, 感谢原作者分享。
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号