晦涩de咚 2016-08-12 10:09:30 6680次浏览 1条评论 8 2 0

起初使用页面缓存,发现使用于含有参数的方法存在弊端,只能缓存第一次的页面,导致后面所有不同参数的页面均显示第一次缓存页面;没有生成一个参数页面一个缓存;于是,进行了重写页面缓存。

<?php 


namespace common\lib;

use Yii;
use yii\caching\Cache;
use yii\di\Instance;
use yii\web\Response;
use yii\filters\PageCache as PCache;


/**
* 重写页面缓存,增加varByParam参数一列
*/
class PageCache extends PCache
{
	/**
	 * 参数设置,默认无参数
	 * 用法:'varByParam' => Yii::$app->request->get('id')
	 * @var string
	 */
	public $varByParam = '';

	public function beforeAction($action)
    {
        if (!$this->enabled) {
            return true;
        }

        $this->cache = Instance::ensure($this->cache, Cache::className());

        if (is_array($this->dependency)) {
            $this->dependency = Yii::createObject($this->dependency);
        }

        $properties = [];
        foreach (['cache', 'duration', 'dependency', 'variations'] as $name) {
            $properties[$name] = $this->$name;
        }
        $id = $this->varyByRoute ? $action->getUniqueId().$this->varByParam : __CLASS__;
        $response = Yii::$app->getResponse();
        ob_start();
        ob_implicit_flush(false);
        if ($this->view->beginCache($id, $properties)) {
            $response->on(Response::EVENT_AFTER_SEND, [$this, 'cacheResponse']);
            return true;
        } else {
            $data = $this->cache->get($this->calculateCacheKey());
            if (is_array($data)) {
                $this->restoreResponse($response, $data);
            }
            $response->content = ob_get_clean();
            return false;
        }
    }
}
 ?>

使用:

[
'class' => 'common\lib\PageCache',
            'only' => ['view'],
            'duration' => 0, //永不过期
            'varByParam' => Yii::$app->request->get('id'),
],

如有不同做法欢迎指正;谢谢!

觉得很赞
  • 评论于 2017-05-21 13:39 举报

    受到楼主的启发,去看了源文件,发现能否缓存带参数页面的关键在于生成缓存key是否唯一。

    我找到的方法如下,编辑文件yii\filters\PageCache.php文件,找到calculateCacheKey()函数。
    编辑$key[]值
    $key[] = Yii::$app->requestedRoute;

    // 可以支持view等带参数页面的缓存。
    $key[] = \Yii::$app->requestedRoute.'/'.implode('/',\Yii::$app->controller->actionParams);
    

    即可对任何带参数的页面进行页面缓存。

    当然,自己写个类,覆盖原来的calculateCacheKey()函数也是可以的。

    觉得很赞
您需要登录后才可以评论。登录 | 立即注册