Yii 2.0 使用片段缓存

网站首页footer中的菜单标题是从数据库读取并显示处理的。

也就是 <footer>标题里面是foreach。这样每个人打开网站就查询遍历效率会很低。

<footer class="footer">
    <div class="container">
        <div class="row">
            <div class="col-lg-10">
                <div class="row">
                    <?php
                    $html = '';
                    $i = 0;
                    $res = ArticleCategory::getHelpArticles();
                    if (!empty($res)) {
                        foreach ($res as $cate) {
                            $i++;
                            $html .= '<div class="col-lg-2"><dl class="col-links col-links-first">';
                            $html .= Html::tag('dt', $cate->attributes['name']);
                            if (!empty($cate->articles)) {
                                foreach ($cate->articles as $article) {
                                    $html .= '<dd>';
                                    $html .= Html::a($article->title, Url::to('/page/' . $article->friendlyUrl));
                                    $html .= '</dd>';
                                }
                                $html .= '</dl>';
                            }
                            $html .= '</dl></div>';
                        }
                    }
                    echo $html;
                    ?>
                </div>
    </div>
</footer>

如果要把footer之间的内容缓存起来。每60分钟刷新一次。这样就会减少很多不必要的查询。

Yii2.0 在缓存方面做的不错,做法非常简单。

开始行动:

footer上方加入

$footerCacheKey = 'footerCache';
if ($this->beginCache($footerCacheKey)) {
?>

<footer class="footer">

footer下方

</footer>
<?php
    $this->endCache();
}

footer属于首页,是由SiteController调用。

在 behaviors() 方法里面加入

    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['logout', 'signup'],
                'rules' => [
                    [
                        'actions' => ['signup'],
                        'allow' => true,
                        'roles' => ['?'],
                    ],
                    [
                        'actions' => ['logout'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
            // 新加入的代码
            'pageCache' => [
                'class' => 'yiifiltersPageCache',
                'only' => ['index'],
                'duration' => 60*60*24,
            ],
        ];
    }

 参考: 

http://www.yiiframework.com/doc-2.0/guide-caching-page.html

http://www.yiiframework.com/doc-2.0/guide-caching-fragment.html

原文地址:https://www.cnblogs.com/mafeifan/p/4339737.html