You are here

public function CacheExampleForm::cacheClearing in Examples for Developers 3.x

Same name and namespace in other branches
  1. 8 cache_example/src/Form/CacheExampleForm.php \Drupal\cache_example\Form\CacheExampleForm::cacheClearing()

Submit handler to demonstrate the various uses of cache_clear_all().

File

modules/cache_example/src/Form/CacheExampleForm.php, line 260

Class

CacheExampleForm
Form with examples on how to use cache.

Namespace

Drupal\cache_example\Form

Code

public function cacheClearing($form, &$form_state) {
  switch ($form_state
    ->getValue('cache_clear_type')) {
    case 'expire':

      // Here we'll remove all cache keys in the 'cache' bin that have
      // expired.
      $this->cacheBackend
        ->garbageCollection();
      $this
        ->messenger()
        ->addMessage($this
        ->t('\\Drupal::cache()->garbageCollection() was called, removing any expired cache items.'));
      break;
    case 'remove_all':

      // This removes all keys in a bin using a super-wildcard. This
      // has nothing to do with expiration. It's just brute-force removal.
      $this->cacheBackend
        ->deleteAll();
      $this
        ->messenger()
        ->addMessage($this
        ->t('ALL entries in the "cache" bin were removed with \\Drupal::cache()->deleteAll().'));
      break;
    case 'remove_tag':

      // This removes cache entries with the tag "cache_example" set to 1 in
      // the "cache".
      $tags = [
        'cache_example:1',
      ];
      Cache::invalidateTags($tags);
      $this
        ->messenger()
        ->addMessage($this
        ->t('Cache entries with the tag "cache_example" set to 1 in the "cache" bin were invalidated with \\Drupal\\Core\\Cache\\Cache::invalidateTags($tags).'));
      break;
  }
}