set() public method

If the cache already contains such a key, the existing value and expiration time will be replaced with the new ones, respectively.
public set ( mixed $key, mixed $value, integer $duration = null, yii\caching\Dependency $dependency = null ) : boolean
$key mixed a key identifying the value to be cached. This can be a simple string or a complex data structure consisting of factors representing the key.
$value mixed the value to be cached
$duration integer default duration in seconds before the cache will expire. If not set, default [[ttl]] value is used.
$dependency yii\caching\Dependency dependency of the cached item. If the dependency changes, the corresponding value in the cache will be invalidated when it is fetched via [[get()]]. This parameter is ignored if [[serializer]] is false.
return boolean whether the value is successfully stored into cache
 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;
 }
Beispiel #2
0
 /**
  * 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();
     }
 }
Beispiel #5
0
 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'];
 }
Beispiel #6
0
 /**
  * @inheritdoc
  */
 protected function acquireLock($name, $timeout = 0)
 {
     if (!$this->cache instanceof Cache) {
         return false;
     }
     $waitTime = 0;
     while ($this->cache->get($this->getCacheKey($name)) !== false) {
         $waitTime++;
         if ($waitTime > $timeout) {
             return false;
         }
         sleep(1);
     }
     return $this->cache->set($this->getCacheKey($name), true);
 }
Beispiel #7
0
 /**
  * @return array
  * @throws \yii\base\InvalidConfigException
  */
 protected function getAllAssignments()
 {
     $result = [];
     $useCache = $this->useCache === true;
     if ($useCache && $this->cache->exists('assignments-0')) {
         echo '    > Assignments cache exists.' . PHP_EOL;
         $answer = $this->prompt('      > Use cache? [yes/no]');
         if (strpos($answer, 'y') === 0) {
             $this->cacheIterator(function ($key) use(&$result) {
                 $result = ArrayHelper::merge($result, $this->cache->get($key));
             });
             return $result;
         }
     }
     /** @var \yii\db\ActiveQuery $UsersQuery */
     $UsersQuery = call_user_func([$this->user->identityClass, 'find']);
     /** @var \yii\web\IdentityInterface[] $Users */
     foreach ($UsersQuery->batch($this->batchSize, $this->db) as $k => $Users) {
         $chunk = [];
         foreach ($Users as $User) {
             $pk = $User->getId();
             $assignments = array_keys($this->authManager->getAssignments($pk));
             $chunk[$pk] = $assignments;
             $result[$pk] = $assignments;
         }
         if ($useCache) {
             $this->cache->set(sprintf('assignments-%d', $k), $chunk);
         }
     }
     return $result;
 }
Beispiel #8
0
 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
 }
Beispiel #9
0
 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();
     }
 }
 protected function load()
 {
     $this->items = $this->cache->get('settings');
     if (!$this->items) {
         $this->items = [];
         $rows = (new Query())->from($this->tableName)->all($this->db);
         foreach ($rows as $row) {
             $this->items[$row['category']][$row['key']] = @unserialize($row['value']);
         }
         $this->cache->set('settings', $this->items, $this->cacheTime);
     }
 }
Beispiel #11
0
 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();
     }
 }
Beispiel #12
0
 /**
  * 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;
 }
 /**
  * 通过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;
 }
Beispiel #15
0
 /**
  * Get list of application routes
  *
  * @param string|null $module
  *
  * @return array
  */
 public function getAppRoutes($module = null)
 {
     if ($module === null) {
         $module = Yii::$app;
     } elseif (is_string($module)) {
         $module = Yii::$app->getModule($module);
     }
     $key = [__METHOD__, $module->getUniqueId()];
     $result = $this->cache !== null ? $this->cache->get($key) : false;
     if ($result === false) {
         $result = [];
         $this->getRouteRecursive($module, $result);
         if ($this->cache !== null) {
             $this->cache->set($key, $result, $this->cacheDuration, new TagDependency(['tags' => self::CACHE_TAG]));
         }
     }
     return $result;
 }
 /**
  * Производит поиск модулей удовлетворяющих условиям запроса
  * @return string[] Modules Ids
  */
 public function find()
 {
     if ($this->cache) {
         $cacheKey = $this->getFindCacheKey();
         if (($result = $this->cache->get($cacheKey)) === false) {
             $modules = $this->findModules($this->_nodeOf ? $this->_nodeOf : Yii::$app);
             if ($this->_orderBy) {
                 usort($modules, [$this, 'compareModules']);
             }
             $result = $this->extractModuleIds($modules);
             $this->cache->set($cacheKey, $result, $this->cacheDuration, $this->cacheDependency);
         }
         return $result;
     }
     $modules = $this->findModules($this->_nodeOf ? $this->_nodeOf : Yii::$app);
     if ($this->_orderBy) {
         usort($modules, [$this, 'compareModules']);
     }
     return $this->extractModuleIds($modules);
 }
Beispiel #17
0
 /**
  * Renders the menu.
  */
 public function run()
 {
     if ($this->route === null && Yii::$app->controller !== null) {
         $this->route = Yii::$app->controller->getRoute();
     }
     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 DesktopEvent(['items' => $this->items]), 'items');
             $this->cache->set($cacheKey, $this->items, $this->cacheDuration, $this->cacheDependency);
         }
     } else {
         $this->items = ModuleEvent::trigger(self::EVENT_FETCH_ITEMS, new DesktopEvent(['items' => $this->items]), 'items');
     }
     $this->normalizeItems();
     $options = $this->options;
     $tag = ArrayHelper::remove($options, 'tag', 'div');
     echo Html::tag($tag, $this->renderItems($this->columns), $options);
 }
Beispiel #18
0
 /**
  * Get OAuth2 token using client credentials granted method.
  * @param boolean $isForce Whether force regenerated token.
  * @return string
  */
 public function getToken($isForce = false)
 {
     if ($this->_token === null || $isForce) {
         $key = __CLASS__ . '#' . $this->clientId . '#token';
         if ($this->cache instanceof Cache && !$isForce) {
             $token = $this->cache->get($key);
             if ($token) {
                 $this->_token = $token['access_token'];
                 goto RESULT;
             }
         }
         $client = $this->getClient();
         $url = static::buildUrl($this->baseUrl, $this->tokenPath);
         $res = $client->post($url, ['json' => ['client_id' => $this->clientId, 'client_secret' => $this->clientSecret, 'grant_type' => 'client_credentials']]);
         $tmp = $res->json();
         $this->_token = $tmp['access_token'];
         if ($this->cache instanceof Cache) {
             $this->cache->set($key, $tmp, $tmp['expires_in'] - 300);
         }
     }
     RESULT:
     return $this->_token;
 }
Beispiel #19
0
 /**
  * 缓存数据
  * @param string $name 缓存Key
  * @param mixed $value 缓存Value
  * @param int $duration 缓存有效时间
  * @return bool
  */
 protected function setCache($name, $value, $duration)
 {
     return $this->cache->set($this->getCacheKey($name), $value, $duration);
 }
Beispiel #20
0
 private function saveToCache($part, $data)
 {
     if ($this->enableCaching) {
         $this->cache->set($this->buildKey($part), $data, $this->cacheDuration, new GroupDependency(['group' => $this->buildGroup($part)]));
     }
 }
 /**
  * @inheritdoc
  */
 public function save()
 {
     $this->yiiCache->set($this->key, $this->getForStorage(), $this->duration);
 }
 /**
  * @param mixed      $key
  * @param mixed      $value
  * @param integer    $duration
  * @param Dependency $dependency
  *
  * @return boolean
  *
  * @see yii\caching\Cache::set()
  */
 public function set($key, $value, $duration = 0, $dependency = NULL)
 {
     return $this->cache->set($key, $value, $duration, $dependency);
 }
Beispiel #23
0
 /**
  * Sets the cache
  */
 private function _setCache()
 {
     if ($this->_cache !== null) {
         $this->_cache->set($this->cacheKey, $this->_data, $this->cacheDuration);
     }
 }
 /**
  * Invalidates all of the cached data items that have the same [[group]].
  * @param Cache $cache the cache component that caches the data items
  * @param string $group the group name
  * @return string the current version number
  */
 public static function invalidate($cache, $group)
 {
     $version = microtime();
     $cache->set([__CLASS__, $group], $version);
     return $version;
 }
Beispiel #25
0
 /**
  * @param $key
  * @param $value
  * @param $duration
  * @return bool
  */
 protected function setCacheData($key, $value, $duration)
 {
     $this->data[$key] = $value;
     return $this->cache->set($key, $value, $duration);
 }