By calling TagDependency::invalidate, you can invalidate all cached data items that are associated with the specified tag name(s).
Since: 2.0
Author: Qiang Xue (qiang.xue@gmail.com)
Inheritance: extends yii\caching\Dependency
 /**
  * @inheritdoc
  */
 public function run()
 {
     if ($this->model === null) {
         throw new InvalidConfigException("Model should be set for WarehousesRemains widget");
     }
     $state = $this->model->getWarehousesState();
     $activeWarehousesIds = Warehouse::activeWarehousesIds();
     $remains = [];
     foreach ($state as $remain) {
         $remains[$remain->warehouse_id] = $remain;
         if (($key = array_search($remain->warehouse_id, $activeWarehousesIds)) !== false) {
             unset($activeWarehousesIds[$key]);
         }
     }
     // if we have new warehouses that not represented in warehouses state
     if (count($activeWarehousesIds) > 0) {
         foreach ($activeWarehousesIds as $id) {
             // create new record with default values
             $remain = new WarehouseProduct();
             $remain->warehouse_id = $id;
             $remain->product_id = $this->model->id;
             $remain->save();
             // add to remains
             $remains[$remain->warehouse_id] = $remain;
         }
         TagDependency::invalidate(Yii::$app->cache, ActiveRecordHelper::getObjectTag($this->model->className(), $this->model->id));
     }
     return $this->render('warehouses-remains', ['model' => $this->model, 'remains' => $remains]);
 }
 public function down()
 {
     $tbl = '{{%backend_menu}}';
     $this->update($tbl, ['route' => '/shop/backend-order/index'], ['route' => 'shop/backend-order/index']);
     $this->update($tbl, ['route' => '/shop/backend-customer/index'], ['route' => 'shop/backend-customer/index']);
     $this->update($tbl, ['route' => '/shop/backend-contragent/index'], ['route' => 'shop/backend-contragent/index']);
     \yii\caching\TagDependency::invalidate(Yii::$app->cache, [\devgroup\TagDependencyHelper\ActiveRecordHelper::getCommonTag(\app\backend\models\BackendMenu::className())]);
 }
 public function down()
 {
     $this->dropTable('{{%addon}}');
     $this->dropTable('{{%addon_category}}');
     $this->dropTable('{{%addon_bindings}}');
     $this->delete('{{%object}}', ['name' => 'Addon']);
     $this->delete('{{%backend_menu}}', ['name' => 'Addons']);
     \yii\caching\TagDependency::invalidate(Yii::$app->cache, [\devgroup\TagDependencyHelper\ActiveRecordHelper::getCommonTag(\app\backend\models\BackendMenu::className())]);
     $this->dropColumn('{{%order_item}}', 'addon_id');
 }
Exemple #4
0
 /**
  * Deletes the cache for the frontend and backend loaded data using makeCacheTag method
  *
  * @param Event $event
  */
 public function _deleteCache(Event $event)
 {
     $frontend = [0, 1];
     $backend = [0, 1];
     foreach ($frontend as $_f) {
         foreach ($backend as $_b) {
             TagDependency::invalidate(Yii::$app->cache, self::makeCacheTag($_f, $_b));
         }
     }
 }
Exemple #5
0
 public function testInvalidate()
 {
     $cache = new FileCache(['cachePath' => '@yiiunit/runtime/cache']);
     // single tag test
     $cache->set('a1', 11, 0, new TagDependency(['tags' => 't1']));
     $cache->set('a2', 12, 0, new TagDependency(['tags' => 't1']));
     $cache->set('b1', 21, 0, new TagDependency(['tags' => 't2']));
     $cache->set('b2', 22, 0, new TagDependency(['tags' => 't2']));
     $this->assertEquals(11, $cache->get('a1'));
     $this->assertEquals(12, $cache->get('a2'));
     $this->assertEquals(21, $cache->get('b1'));
     $this->assertEquals(22, $cache->get('b2'));
     TagDependency::invalidate($cache, 't1');
     $this->assertFalse($cache->get('a1'));
     $this->assertFalse($cache->get('a2'));
     $this->assertEquals(21, $cache->get('b1'));
     $this->assertEquals(22, $cache->get('b2'));
     TagDependency::invalidate($cache, 't2');
     $this->assertFalse($cache->get('a1'));
     $this->assertFalse($cache->get('a2'));
     $this->assertFalse($cache->get('b1'));
     $this->assertFalse($cache->get('b2'));
     // multiple tag test
     $cache->set('a1', 11, 0, new TagDependency(['tags' => ['t1', 't2']]));
     $cache->set('a2', 12, 0, new TagDependency(['tags' => 't1']));
     $cache->set('b1', 21, 0, new TagDependency(['tags' => ['t1', 't2']]));
     $cache->set('b2', 22, 0, new TagDependency(['tags' => 't2']));
     $this->assertEquals(11, $cache->get('a1'));
     $this->assertEquals(12, $cache->get('a2'));
     $this->assertEquals(21, $cache->get('b1'));
     $this->assertEquals(22, $cache->get('b2'));
     TagDependency::invalidate($cache, 't1');
     $this->assertFalse($cache->get('a1'));
     $this->assertFalse($cache->get('a2'));
     $this->assertFalse($cache->get('b1'));
     $this->assertEquals(22, $cache->get('b2'));
     TagDependency::invalidate($cache, 't2');
     $this->assertFalse($cache->get('a1'));
     $this->assertFalse($cache->get('a2'));
     $this->assertFalse($cache->get('b1'));
     $this->assertFalse($cache->get('b2'));
     $cache->set('a1', 11, 0, new TagDependency(['tags' => ['t1', 't2']]));
     $cache->set('a2', 12, 0, new TagDependency(['tags' => 't1']));
     $cache->set('b1', 21, 0, new TagDependency(['tags' => ['t1', 't2']]));
     $cache->set('b2', 22, 0, new TagDependency(['tags' => 't2']));
     $this->assertEquals(11, $cache->get('a1'));
     $this->assertEquals(12, $cache->get('a2'));
     $this->assertEquals(21, $cache->get('b1'));
     $this->assertEquals(22, $cache->get('b2'));
     TagDependency::invalidate($cache, ['t1', 't2']);
     $this->assertFalse($cache->get('a1'));
     $this->assertFalse($cache->get('a2'));
     $this->assertFalse($cache->get('b1'));
     $this->assertFalse($cache->get('b2'));
 }
 public function setCustomization($block, $customization = [])
 {
     $this->validateBemSelector($block);
     static::$identityMap[$block] = $customization;
     $filename = $this->storagePath . $block . 'json';
     $result = file_put_contents($filename, Json::encode($customization)) !== false;
     if ($result === true) {
         TagDependency::invalidate(Yii::$app->cache, ["GlobalCustomization:{$block}"]);
     }
     return $result;
 }
 /**
  * @inheritdoc
  */
 public function run()
 {
     $n = 0;
     switch ($this->action) {
         case CategoryMovementsButtons::ADD_ACTION:
             $n = $this->add();
             break;
         case CategoryMovementsButtons::MOVE_ACTION:
             $n = $this->move();
             break;
     }
     $tags = [];
     foreach ($this->items as $id) {
         $tags[] = ActiveRecordHelper::getObjectTag(Product::className(), $id);
     }
     TagDependency::invalidate(Yii::$app->cache, $tags);
     Yii::$app->session->setFlash('info', Yii::t('app', 'Items updated: {n}', ['n' => $n]));
 }
 /**
  * Переносик категорию
  * @param $parent integer
  * @param $position integer
  * @return array
  */
 public function moveCategory($parent, $position)
 {
     // Очищаем ВСЕ кеши категорий
     TagDependency::invalidate(Yii::$app->cache, ['category']);
     $result = false;
     $counts = [];
     $parentCat = Category::findOne($parent);
     // Новый родитель
     $oldParentCat = Category::findOne($this->parent);
     // Старый родитель
     $this->parent = $parent;
     // Если position = 0
     if ($position === 0) {
         // Добавляем в начало
         $result = $this->prependTo($parentCat);
     } else {
         // Иначе, ищем категорию, после которой нужно добавить
         $prevCategory = end($parentCat->children(1)->andWhere(['not in', 'id', $this->id])->limit($position)->all());
         // Если нужный элемент найден
         if ($prevCategory !== null) {
             // Добавляем новый после нее
             $result = $this->insertAfter($prevCategory);
         }
     }
     // Пересчитываем cnt_products для всех НОВЫХ и СТАРЫХ родительских категорий
     // Если товаров в категории нет, то и пересчитывать ничего не нужно
     if (0 < $this->cnt_products) {
         $parents = array_unique(array_merge([$oldParentCat->id], Category::getParentsIds($oldParentCat->id), [(int) $this->parent], Category::getParentsIds($this->parent)));
         foreach ($parents as $p) {
             $parentCategory = Category::findOne($p);
             $parentCategory->cnt_products = Product::findAllInCatsAndSubCategories($parentCategory)->count();
             $parentCategory->save();
             $counts[$parentCategory->id] = $parentCategory->cnt_products;
         }
     }
     return ['result' => $result, 'counts' => $counts];
 }
Exemple #9
0
 /**
  * Ivalidate cache
  */
 protected function invalidate()
 {
     if (Configs::instance()->cache !== null) {
         TagDependency::invalidate(Configs::instance()->cache, self::CACHE_TAG);
     }
 }
Exemple #10
0
 /**
  * @inheritdoc
  */
 public function beforeSave($insert)
 {
     if (!$insert) {
         // reset a cache tag to get a new parent model below
         TagDependency::invalidate(Yii::$app->cache, [ActiveRecordHelper::getCommonTag(self::className())]);
     }
     $this->slug_compiled = $this->compileSlug();
     TagDependency::invalidate(Yii::$app->cache, [ActiveRecordHelper::getCommonTag($this->className()), 'Page:' . $this->slug_compiled]);
     TagDependency::invalidate(Yii::$app->cache, [ActiveRecordHelper::getCommonTag($this->className()), 'Page:' . $this->id . ':0']);
     TagDependency::invalidate(Yii::$app->cache, [ActiveRecordHelper::getCommonTag($this->className()), 'Page:' . $this->id . ':1']);
     if (empty($this->breadcrumbs_label)) {
         $this->breadcrumbs_label = $this->title;
     }
     if (empty($this->h1)) {
         $this->h1 = $this->title;
     }
     return parent::beforeSave($insert);
 }
 /**
  * Ivalidate cache
  */
 public static function invalidate()
 {
     if (Configs::cache() !== null) {
         TagDependency::invalidate(Configs::cache(), self::CACHE_TAG);
     }
 }
 public function invalidateCache()
 {
     TagDependency::invalidate(Yii::$app->cache, self::$cacheKey);
 }
 /**
  * Deletes an existing Book model.
  * If deletion is successful, the browser will be redirected to the 'index' page.
  * @param integer $id
  * @return mixed
  */
 public function actionDelete($id)
 {
     $this->findModel($id)->delete();
     \yii\caching\TagDependency::invalidate(Yii::$app->cache, 'books');
     return $this->redirect(['index']);
 }
 /**
  * Invalidate cache
  */
 public function afterDelete()
 {
     TagDependency::invalidate(Yii::$app->cache, ContentModule::CACHE_TAG);
     parent::afterDelete();
 }
Exemple #15
0
 static function delete($tags = '')
 {
     TagDependency::invalidate(Yii::$app->cache, $tags);
 }
Exemple #16
0
 public function beforeSave($insert)
 {
     if (empty($this->breadcrumbs_label)) {
         $this->breadcrumbs_label = $this->name;
     }
     if (empty($this->h1)) {
         $this->h1 = $this->name;
     }
     if (empty($this->title)) {
         $this->title = $this->name;
     }
     $object = Object::getForClass(static::className());
     \yii\caching\TagDependency::invalidate(Yii::$app->cache, ['Images:' . $object->id . ':' . $this->id]);
     return parent::beforeSave($insert);
 }
 /**
  *
  */
 protected function invalidateTags()
 {
     TagDependency::invalidate($this->getCache(), array_map(function ($tag) {
         if (is_callable($tag)) {
             $tag = call_user_func($tag, $this->owner);
         }
         return $tag;
     }, $this->tags));
 }
Exemple #18
0
 /**
  * Refresh cms widget
  * @param int $id Widget ID
  */
 public static function refreshWidget($id)
 {
     TagDependency::invalidate(Yii::$app->commonCache, self::getCacheTag($id));
 }
Exemple #19
0
 /**
  * Refresh file cache
  * @static
  */
 public static function refreshFileCache()
 {
     if (($cache = Yii::$app->getCache()) !== null) {
         TagDependency::invalidate($cache, static::getGroup(static::FILE_GROUP));
     }
 }
Exemple #20
0
 /**
  *
  */
 public function invalidateModelCache()
 {
     TagDependency::invalidate(Yii::$app->cache, [ActiveRecordHelper::getObjectTag(PropertyGroup::className(), $this->property_group_id), ActiveRecordHelper::getObjectTag(Property::className(), $this->id)]);
 }
Exemple #21
0
 /**
  * Refreshes the schema.
  * This method cleans up all cached table schemas so that they can be re-created later
  * to reflect the database schema change.
  */
 public function refresh()
 {
     /* @var $cache Cache */
     $cache = is_string($this->db->schemaCache) ? Yii::$app->get($this->db->schemaCache, false) : $this->db->schemaCache;
     if ($this->db->enableSchemaCache && $cache instanceof Cache) {
         TagDependency::invalidate($cache, $this->getCacheTag());
     }
     $this->_tableNames = [];
     $this->_tables = [];
 }
 /**
  *
  */
 public static function clearProductList()
 {
     yii\caching\TagDependency::invalidate(Yii::$app->cache, ['Session:' . Yii::$app->session->id]);
     Yii::$app->session->remove(static::SESSION_COMPARE_LIST);
 }
Exemple #23
0
 /**
  * При любом обновлении, сохранении, удалении записей в эту таблицу, инвалидируется тэг кэша таблицы
  * @return $this
  */
 public function invalidateTableCache()
 {
     TagDependency::invalidate($this->cache, [$this->getTableCacheTag()]);
     return $this;
 }
Exemple #24
0
 /**
  * @inheritdoc
  */
 public function afterSave($insert, $changedAttributes)
 {
     TagDependency::invalidate(Yii::$app->cache, ['Session:' . Yii::$app->session->id]);
     parent::afterSave($insert, $changedAttributes);
     if (!$insert && !empty($changedAttributes['user_id']) && 0 === intval($changedAttributes['user_id'])) {
         if (!empty($this->customer)) {
             $customer = $this->customer;
             $customer->user_id = 0 === intval($customer->user_id) ? $this->user_id : $customer->user_id;
             $customer->save();
         }
     }
 }
 private function invalidateTags($className, $ids)
 {
     $tags = [ActiveRecordHelper::getCommonTag($className)];
     foreach ($ids as $id) {
         $tags[] = ActiveRecordHelper::getObjectTag($className, $id);
     }
     \yii\caching\TagDependency::invalidate(Yii::$app->cache, $tags);
 }
 /**
  * Success callback for social networks authentication
  * @param $client
  * @throws ErrorException
  * @throws \yii\base\ExitException
  */
 public function successCallback($client)
 {
     $model = AuthClientHelper::findUserByService($client);
     if (is_object($model) === false) {
         // user not found, retrieve additional data
         $client = AuthClientHelper::retrieveAdditionalData($client);
         $attributes = AuthClientHelper::mapUserAttributesWithService($client);
         // check if it is anonymous user
         if (Yii::$app->user->isGuest === true) {
             $model = new User(['scenario' => 'registerService']);
             $security = Yii::$app->security;
             $model->setAttributes($attributes['user']);
             $model->status = User::STATUS_ACTIVE;
             if (empty($model->username) === true) {
                 // if we doesn't have username - generate unique random temporary username
                 // it will be needed for saving purposes
                 $model->username = $security->generateRandomString(18);
                 $model->username_is_temporary = 1;
             }
             $model->setPassword($security->generateRandomString(16));
             $model->generateAuthKey();
             if ($model->save() === false) {
                 if (isset($model->errors['username'])) {
                     // regenerate username
                     $model->username = $security->generateRandomString(18);
                     $model->username_is_temporary = 1;
                     $model->save();
                 }
                 if (isset($model->errors['email'])) {
                     // empty email
                     $model->email = null;
                     $model->save();
                 }
                 if (count($model->errors) > 0) {
                     throw new ErrorException(Yii::t('app', "Temporary error signing up user"));
                 }
             }
         } else {
             // non anonymous - link to existing account
             /** @var \app\modules\user\models\User $model */
             $model = Yii::$app->user->identity;
         }
         $service = new UserService();
         $service->service_type = $client->className();
         $service->service_id = '' . $attributes['service']['service_id'];
         $service->user_id = $model->id;
         if ($service->save() === false) {
             throw new ErrorException(Yii::t('app', "Temporary error saving social service"));
         }
     } elseif (Yii::$app->user->isGuest === false) {
         // service exists and user logged in
         // check if this service is binded to current user
         if ($model->id != Yii::$app->user->id) {
             throw new ErrorException(Yii::t('app', "This service is already binded to another user"));
         } else {
             throw new ErrorException(Yii::t('app', 'This service is already binded.'));
         }
     }
     TagDependency::invalidate(Yii::$app->cache, ['Session:' . Yii::$app->session->id]);
     Yii::$app->user->login($model, 86400);
     if ($model->username_is_temporary == 1 || empty($model->email)) {
         // show post-registration form
         $this->layout = $this->module->postRegistrationLayout;
         $model->setScenario('completeRegistration');
         echo $this->render('post-registration', ['model' => $model]);
         Yii::$app->end();
         return;
     }
 }
 /**
  * Invalidate cache
  * @param string $parts
  */
 private function invalidate($parts)
 {
     if ($this->enableCaching) {
         TagDependency::invalidate($this->cache, $parts);
     }
 }
 /**
  * @param \app\modules\config\models\Configurable[] $configurables
  * @param bool $usePostData
  * @return bool
  */
 public static function updateConfiguration(&$configurables, $usePostData = true, $loadExistingConfiguration = true)
 {
     $commonConfigWriter = new ApplicationConfigWriter(['filename' => '@app/config/common-configurables.php', 'loadExistingConfiguration' => $loadExistingConfiguration]);
     $webConfigWriter = new ApplicationConfigWriter(['filename' => '@app/config/web-configurables.php', 'loadExistingConfiguration' => $loadExistingConfiguration]);
     $consoleConfigWriter = new ApplicationConfigWriter(['filename' => '@app/config/console-configurables.php', 'loadExistingConfiguration' => $loadExistingConfiguration]);
     $kvConfigWriter = new ApplicationConfigWriter(['filename' => '@app/config/kv-configurables.php', 'loadExistingConfiguration' => $loadExistingConfiguration]);
     $aliasesConfigWriter = new ApplicationConfigWriter(['filename' => '@app/config/aliases.php', 'loadExistingConfiguration' => $loadExistingConfiguration]);
     $isValid = true;
     $errorModule = '';
     foreach ($configurables as $model) {
         $configurableModel = $model->getConfigurableModel();
         $configurableModel->loadState();
         $dataOk = true;
         if ($usePostData === true) {
             $dataOk = $configurableModel->load(Yii::$app->request->post());
         }
         if ($dataOk === true) {
             $event = new ConfigurationSaveEvent();
             $event->configurable =& $model;
             $event->configurableModel =& $configurableModel;
             $configurableModel->trigger($configurableModel->configurationSaveEvent(), $event);
             if ($event->isValid === true) {
                 if ($configurableModel->validate() === true) {
                     // apply application configuration
                     $commonConfigWriter->addValues($configurableModel->commonApplicationAttributes());
                     $webConfigWriter->addValues($configurableModel->webApplicationAttributes());
                     $consoleConfigWriter->addValues($configurableModel->consoleApplicationAttributes());
                     $kvConfigWriter->addValues(['kv-' . $model->module => $configurableModel->keyValueAttributes()]);
                     $aliasesConfigWriter->addValues($configurableModel->aliases());
                     $configurableModel->saveState();
                     if (isset(Yii::$app->modules[$model->module]) === true) {
                         /** @var \yii\base\Module $module */
                         $module = Yii::$app->modules[$model->module];
                         // invalidate cache by module class name tag
                         TagDependency::invalidate(Yii::$app->cache, [ActiveRecordHelper::getCommonTag($module->className())]);
                     }
                 } else {
                     Yii::$app->session->setFlash('info', 'Validation error:' . var_export($configurableModel));
                     $isValid = false;
                 }
             } else {
                 $isValid = false;
             }
             if ($isValid === false) {
                 $errorModule = $model->module;
                 // event is valid, stop saving data
                 break;
             }
         }
         // model load from user input
     }
     // /foreach
     if ($isValid === true) {
         // add aliases to common config
         $isValid = $commonConfigWriter->commit() && $webConfigWriter->commit() && $consoleConfigWriter->commit() && $kvConfigWriter->commit() && $aliasesConfigWriter->commit();
         if (ini_get('opcache.enable')) {
             // invalidate opcache of this files!
             opcache_invalidate(Yii::getAlias($commonConfigWriter->filename), true);
             opcache_invalidate(Yii::getAlias($webConfigWriter->filename), true);
             opcache_invalidate(Yii::getAlias($consoleConfigWriter->filename), true);
             opcache_invalidate(Yii::getAlias($kvConfigWriter->filename), true);
             opcache_invalidate(Yii::getAlias($aliasesConfigWriter->filename), true);
         }
     }
     if (Yii::$app->get('session', false)) {
         if ($isValid === true) {
             Yii::$app->session->setFlash('success', Yii::t('app', 'Configuration saved'));
         } else {
             Yii::$app->session->setFlash('error', Yii::t('app', 'Error saving configuration for module {module}', ['module' => $errorModule]));
         }
     }
     return $isValid;
 }
 /**
  * @param $id
  * @param $tag
  * @return \yii\web\Response
  * @throws \yii\base\InvalidConfigException
  * @throws HttpException
  */
 public function actionFlushCacheTag($id, $tag)
 {
     TagDependency::invalidate($this->getCache($id), $tag);
     \Yii::$app->session->setFlash('alert', ['body' => \Yii::t('backend', 'TagDependency was invalidated'), 'options' => ['class' => 'alert-success']]);
     return $this->redirect(['index']);
 }
 /**
  * @return bool
  */
 public function beforeDelete()
 {
     // Сбрасываем кэш
     if (Yii::$app->getModule($this->moduleId)->useCache) {
         TagDependency::invalidate(Yii::$app->cache, $this->className());
     }
     return parent::beforeDelete();
 }