A data item can be stored in the cache by calling Cache::set and be retrieved back
later (in the same or different request) by Cache::get. In both operations,
a key identifying the data item is required. An expiration time and/or a [[Dependency|dependency]]
can also be specified when calling Cache::set. If the data item expires or the dependency
changes at the time of calling Cache::get, the cache will return no data.
A typical usage pattern of cache is like the following:
php
$key = 'demo';
$data = $cache->get($key);
if ($data === false) {
...generate $data here...
$cache->set($key, $data, $duration, $dependency);
}
Because Cache implements the [[\ArrayAccess]] interface, it can be used like an array. For example,
php
$cache['foo'] = 'some data';
echo $cache['foo'];
Derived classes should implement the following methods which do the actual cache storage operations:
- Cache::getValue: retrieve the value with a key (if any) from cache
- Cache::setValue: store the value with a key into cache
- Cache::addValue: store the value only if the cache does not have this key before
- Cache::deleteValue: delete the value with the specified key from cache
- Cache::flushValues: delete all values from cache
/** * @inheritdoc */ protected function releaseLock($name) { if (!$this->cache instanceof Cache) { return false; } return $this->cache->delete($this->getCacheKey($name)); }
public function buildSitemapUrl($name) { $urls = $this->urls; $sitemapData = $this->createControllerByID('default')->renderPartial('sitemap', ['urls' => $urls]); $this->cacheProvider->set($this->cacheKey, $sitemapData, $this->cacheExpire); return $sitemapData; }
/** * Build and cache a site map. * @return string * @throws \yii\base\InvalidConfigException */ public function buildSitemap() { $urls = $this->urls; foreach ($this->arrays as $key => $value) { $arrayUrl = []; if (is_callable($value)) { $arrayUrl = call_user_func($value); } else { $arrayUrl = $value; } $urls = array_merge($urls, $arrayUrl); } foreach ($this->models as $modelName) { /** @var behaviors\SitemapBehavior $model */ if (is_array($modelName)) { $model = new $modelName['class'](); if (isset($modelName['behaviors'])) { $model->attachBehaviors($modelName['behaviors']); } } else { $model = new $modelName(); } $urls = array_merge($urls, $model->generateSiteMap()); } $sitemapData = $this->createControllerByID('default')->renderPartial('index', ['urls' => $urls]); $this->cacheProvider->set($this->cacheKey, $sitemapData, $this->cacheExpire); return $sitemapData; }
public function endGathering() { array_pop($this->cacheStack); $elements = $this->elements[$this->currentStackId]; Yii::trace('End gathering:' . $this->currentStackId); $dependencies = array_pop($this->cacheStackDependencies); $this->cache->set($this->getCacheKey(), $elements, $this->cacheLifetime, $dependencies); unset($this->elements[$this->currentStackId]); $stack = $this->cacheStack; $this->currentStackId = end($stack); return $elements; }
/** * @throws InvalidConfigException */ public function init() { if ($this->cache) { /** @var Cache $cache */ $this->cache = Instance::ensure($this->cache, Cache::className()); $cacheKey = __CLASS__; if (($this->_paramsInfo = $this->cache->get($cacheKey)) === false) { $this->_paramsInfo = $this->fetchParamsInfo(); $this->cache->set($cacheKey, $this->_paramsInfo, $this->cacheDuration, $this->cacheDependency); } } else { $this->_paramsInfo = $this->fetchParamsInfo(); } }
public function getToken($userId, $name, $portraitUri) { $cacheKey = 'token:' . serialize([strval($userId), strval($name), strval($portraitUri)]); if (!$this->cache instanceof Cache || false == ($results = $this->cache->get($cacheKey)) || !isset($results['token'])) { $response = $this->request('/user/getToken', ['userId' => $this->getUserAlias($userId), 'name' => $name, 'portraitUri' => $portraitUri]); $results = Json::decode($response, true); if (!isset($results['code']) || 200 != $results['code']) { throw new ResultException($response, '获取token失败'); } if ($this->cache instanceof Cache) { $this->cache->set($cacheKey, $results, $this->tokenCacheDuration); } } return $results['token']; }
/** * @throws \yii\base\InvalidConfigException */ public function init() { parent::init(); if (!empty($this->cache)) { $this->cache = Instance::ensure($this->cache, Cache::className()); } }
public function beforeAction($action) { if (!$this->enabled) { return true; } $this->cache = Instance::ensure($this->cache, Cache::className()); $this->cache->cachePath = Yii::getAlias($this->cachePath) . '/' . $action->getUniqueId(); 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() : __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; } }
/** * Initializes the DbMessageSource component. * This method will initialize the [[db]] property to make sure it refers to a valid DB connection. * Configured [[cache]] component would also be initialized. * @throws InvalidConfigException if [[db]] is invalid or [[cache]] is invalid. */ public function init() { parent::init(); $this->db = Instance::ensure($this->db, Connection::className()); if ($this->enableCaching) { $this->cache = Instance::ensure($this->cache, Cache::className()); } }
/** * Initialize the component */ public function init() { parent::init(); if ($this->cache !== null) { $this->cache = Instance::ensure($this->cache, Cache::className()); } $this->model = new $this->modelClass(); }
/** * Initializes this component by ensuring the existence of the cache path. */ public function init() { parent::init(); $this->cachePath = Yii::getAlias($this->cachePath); if (!is_dir($this->cachePath)) { FileHelper::createDirectory($this->cachePath, $this->dirMode, true); } }
/** * Initializes this application component. * It checks if extension required is loaded. */ public function init() { parent::init(); $extension = $this->useApcu ? 'apcu' : 'apc'; if (!extension_loaded($extension)) { throw new InvalidConfigException("ApcCache requires PHP {$extension} extension to be loaded."); } }
public function actionFlushCache($component = 'cache') { /** @var Cache $cache */ $cache = Instance::ensure($component, Cache::className()); $cache->flush(); Yii::$app->session->setFlash(Alert::TYPE_SUCCESS, Yii::t('gromver.platform', 'Cache flushed.')); return $this->redirect(['index']); }
/** * Singleton construct. */ protected function __construct() { try { $this->cache = Instance::ensure($this->cache, DefaultCache::className()); } catch (Exception $e) { $this->cache = new DummyCache(); } }
public function run() { if ($this->cache) { /** @var Cache $cache */ $this->cache = Instance::ensure($this->cache, Cache::className()); $cacheKey = [__CLASS__, $this->items]; if (($this->items = $this->cache->get($cacheKey)) === false) { $this->items = ModuleEvent::trigger(self::EVENT_FETCH_ITEMS, new MenuItemsEvent(['items' => $this->items]), 'items'); $this->cache->set($cacheKey, $this->items, $this->cacheDuration, $this->cacheDependency); } } else { $this->items = ModuleEvent::trigger(self::EVENT_FETCH_ITEMS, new MenuItemsEvent(['items' => $this->items]), 'items'); } $this->items += $this->customItems; parent::run(); // TODO: Change the autogenerated stub }
public function init() { if ($this->cache) { /** @var Cache $cache */ $this->cache = Instance::ensure($this->cache, Cache::className()); $cacheKey = __CLASS__; if ((list($paths, $routes, $links) = $this->cache->get($cacheKey)) === false) { $this->createMap(); $this->cache->set($cacheKey, [$this->_paths, $this->_routes, $this->_links], $this->cacheDuration, $this->cacheDependency); } else { $this->_paths = $paths; $this->_routes = $routes; $this->_links = $links; } } else { $this->createMap(); } }
/** * 初始化组件 */ public function init() { parent::init(); if ($this->cache !== null) { $this->cache = Instance::ensure($this->cache, Cache::className()); } else { throw new InvalidConfigException("Cache must be turned on"); } self::$wechat = $this; }
/** * Initializes the DbCache component. * This method will initialize the [[db]] property to make sure it refers to a valid DB connection. * @throws InvalidConfigException if [[db]] is invalid. */ public function init() { parent::init(); if (is_string($this->db)) { $this->db = Yii::$app->getComponent($this->db); } if (!$this->db instanceof Connection) { throw new InvalidConfigException("DbCache::db must be either a DB connection instance or the application component ID of a DB connection."); } }
/** * Initializes the FragmentCache object. */ public function init() { parent::init(); $this->cache = $this->enabled ? Instance::ensure($this->cache, Cache::className()) : null; if ($this->getCachedContent() === false) { $this->getView()->cacheStack[] = $this; ob_start(); ob_implicit_flush(false); } }
/** * Initialization of cache component. * @throws InvalidConfigException if cacheComponent is incorrect. */ protected function initCacheComponent() { if ($this->cacheComponent === null || is_array($this->cacheComponent)) { $this->cacheComponent = Yii::createObject(array_merge(['class' => FileCache::className(), 'cachePath' => rtrim($this->compiledPath, '\\/') . '/cache', 'fileMode' => $this->fileMode, 'dirMode' => $this->mkDirMode], $this->cacheComponent ?: [])); } elseif (is_string($this->cacheComponent)) { $this->cacheComponent = Yii::$app->get($this->cacheComponent); } if ($this->cacheComponent !== false && !$this->cacheComponent instanceof Cache) { throw new InvalidConfigException('Incorrect value of ' . __CLASS__ . '::$cacheComponent param. Calculated value of this param must be an instance of ' . Cache::className() . '.'); } }
public function init() { if (!$this->language) { throw new InvalidConfigException(get_called_class() . '::language must be set.'); } if ($this->cache) { /** @var Cache $cache */ $this->cache = Instance::ensure($this->cache, Cache::className()); $cacheKey = [__CLASS__, $this->language]; if ((list($paths, $routes, $links) = $this->cache->get($cacheKey)) === false) { $this->createMap(); $this->cache->set($cacheKey, [$this->_paths, $this->_routes, $this->_links], $this->cacheDuration, $this->cacheDependency); } else { $this->_paths = $paths; $this->_routes = $routes; $this->_links = $links; } } else { $this->createMap(); } }
/** * 通过API查询IP信息 * @param null $ip * @return IpData|mixed */ public function get($ip = null) { $ip = $ip === null ? Yii::$app->request->userIP : $ip; $ipData = new IpData(); $cacheKey = $this->getCacheKey($ip); if ($this->cache !== null && ($json = $this->cache->get($cacheKey))) { $ipData->setAttributes(json_decode($json, true), false); return $ipData; } $context = stream_context_create(['http' => ['timeout' => 1]]); $url = $this->_url . $ip; try { $result = json_decode(file_get_contents($url, 0, $context), true); } catch (Exception $e) { $result = null; } if ($result && $result['code'] == 0) { $ipData->setAttributes($result['data'], false); $this->cache !== null && $this->cache->set($cacheKey, json_encode($ipData), $this->cacheDuration); } return $ipData; }
/** * @param callable $callback */ protected function cacheIterator($callback) { $i = 0; while (true) { $key = sprintf('assignments-%d', $i); if ($this->cache->exists($key)) { call_user_func($callback, $key); } else { break; } $i++; } }
/** * Build and cache a site map. * @param bool $returnAsArray * @return array|string * @throws InvalidConfigException */ public function buildSitemap($returnAsArray = false) { $urls = $this->urls; foreach ($this->models as $modelName) { /** @var \kato\modules\sitemap\behaviors\SitemapBehavior $model */ if (is_array($modelName)) { $model = new $modelName['class'](); if (isset($modelName['behaviors'])) { $model->attachBehaviors($modelName['behaviors']); } } else { $model = new $modelName(); } $urls = array_merge($urls, $model->generateSiteMap()); } if ($returnAsArray === true) { return $urls; } $sitemapData = $this->createControllerByID('default')->renderPartial('index', ['urls' => $urls]); $this->cacheProvider->set($this->cacheKey, $sitemapData, $this->cacheExpire); return $sitemapData; }
/** * Build and cache a yandex.market yml * @return string */ public function buildYml() { $shop = new Shop(); $shop->attributes = $this->shopOptions; $categoryModel = new $this->categoryModel(); $shop->categories = $categoryModel->generateCategories(); foreach ($this->offerModels as $modelName) { /** @var YmlOfferBehavior $model */ if (is_array($modelName)) { $model = new $modelName['class'](); } else { $model = new $modelName(); } $shop->offers = array_merge($shop->offers, $model->generateOffers()); } if (!$shop->validate()) { return $this->createControllerByID('default')->renderPartial('errors', ['shop' => $shop]); } $ymlData = $this->createControllerByID('default')->renderPartial('index', ['shop' => $shop]); $this->cacheProvider->set($this->cacheKey, $ymlData, $this->cacheExpire); return $ymlData; }
/** * Initializes the HSCache component. * This method will initialize the [[db]] property to make sure it refers to a valid DB connection. * @throws InvalidConfigException if [[db]] is invalid. */ public function init() { parent::init(); switch ($this->mode) { case 'multiType': $this->hs = new \HSLib\CacheMultiType($this->host . ':' . $this->portRead, $this->secret, $this->host . ':' . $this->portWrite, $this->secret, $this->db, $this->table, $this->debug); break; case 'multiTable': $this->hs = new \HSLib\CacheMultiTable($this->host . ':' . $this->portRead, $this->secret, $this->host . ':' . $this->portWrite, $this->secret, $this->db, $this->debug); break; default: throw new InvalidConfigException('Wrong mode in ' . HSCache::className()); } }
/** * Initializes the redis Cache component. * This method will initialize the [[redis]] property to make sure it refers to a valid redis connection. * @throws InvalidConfigException if [[redis]] is invalid. */ public function init() { parent::init(); if (is_string($this->redis)) { $this->redis = Yii::$app->get($this->redis); } elseif (is_array($this->redis)) { if (!isset($this->redis['class'])) { $this->redis['class'] = Connection::className(); } $this->redis = Yii::createObject($this->redis); } if (!$this->redis instanceof Connection) { throw new InvalidConfigException("Cache::redis must be either a Redis connection instance or the application component ID of a Redis connection."); } }
public function init() { parent::init(); $this->_initOptions(); if ($this->cache) { /** @var Cache $cache */ $this->cache = Instance::ensure($this->cache, Cache::className()); $cacheKey = [__CLASS__, $this->items]; if (($this->items = $this->cache->get($cacheKey)) === false) { $this->items = ModuleEvent::trigger(self::EVENT_FETCH_ITEMS, new MenuItemsEvent(['items' => $this->items]), 'items'); $this->cache->set($cacheKey, $this->items, $this->cacheDuration, $this->cacheDependency); } } else { $this->items = ModuleEvent::trigger(self::EVENT_FETCH_ITEMS, new MenuItemsEvent(['items' => $this->items]), 'items'); } }
public function init() { if ($this->cache) { /** @var Cache $cache */ $this->cache = Instance::ensure($this->cache, Cache::className()); $cacheKey = __CLASS__; if ((list($createUrlRules, $parseUrlRules) = $this->cache->get($cacheKey)) === false) { $this->buildRules(); $this->cache->set($cacheKey, [$this->_createUrlRules, $this->_parseUrlRules]); } else { $this->_createUrlRules = $createUrlRules; $this->_parseUrlRules = $parseUrlRules; } } else { $this->buildRules(); } }
protected function commit() { /* @fixme: implement batch operations */ foreach ($this->toRemove as $category => $keyvalue) { foreach ($keyvalue as $key => $value) { $this->db->createCommand()->delete($this->tableName, ['category' => $category, 'key' => $key])->execute(); } } foreach ($this->toSave as $category => $keyvalue) { foreach ($keyvalue as $key => $value) { $obj = (new Query())->from($this->tableName)->where(['category' => $category, 'key' => $key])->one($this->db); $command = $this->db->createCommand(); if ($obj) { $command = $command->update($this->tableName, ['value' => @serialize($value)], ['category' => $category, 'key' => $key]); } else { $command = $command->insert($this->tableName, ['category' => $category, 'key' => $key, 'value' => @serialize($value)]); } $command->execute(); } } if (count($this->toRemove) + count($this->toSave) > 0) { $this->cache->delete('settings'); } $this->toRemove = []; $this->toSave = []; }