Redis.php 1.58 KB
<?php
namespace common\components\pagecache;

use Yii;
use common\components\cachekey\Parser;

/**
 * @author wuxiao
 * @date 2016-8-23
 */
class Redis extends \yii\redis\Cache
{
    
    public function init()
    {
        if (isset(Yii::$app->params['enableCache']) && !Yii::$app->params['enableCache'])
        {
            Yii::$app->db->enableQueryCache = false;
            Yii::$app->db->enableSchemaCache = false;
        }
        parent::init();
    }
    
    public function buildKey($key)
    {
        if ($key instanceof Parser){
            $key = $key->key();
        }
        return parent::buildKey($key);
    }

    /**
     * @inheritdoc
     */
    protected function getValue($key)
    {
        if (isset(Yii::$app->params['enableCache']) && !Yii::$app->params['enableCache'])
        { 
            Yii::$app->response->headers->set('X-PageCache', 'DISABLE');
            return false;
        }
        $result = parent::getValue($key);
        if ($result){
            Yii::$app->response->headers->add('X-PageCache', 'HIT');
        }else{
            Yii::$app->response->headers->add('X-PageCache', 'MISS');
        }
        return $result;
    }

    /**
     * @inheritdoc
     */
    protected function setValue($key, $value, $expire)
    {
        if (isset(Yii::$app->params['enableCache']) && !Yii::$app->params['enableCache'])
        { 
            Yii::$app->response->headers->set('X-PageCache', 'DISABLE');
            return true;
        }
        Yii::$app->response->headers->add('X-PageCache', 'SAVE');
        return parent::setValue($key, $value, $expire);
    }
}