Drupal8缓存

By admin, 22 十一月, 2019

1. 管理匿名用户Form页面缓存

use Drupal\Core\Cache\Cache;

// 在匿名用户可以访问的表单里加入下面逻辑,包括列表页面和具体的查看页面

    $form['#cache']['tags'] = ['your_custom_tag_name'];

// 在写入逻辑里让缓存失效
    Cache::invalidateTags(['your_custom_tag_name']);

2. 禁用匿名用户Form页面缓存

在<module>.routing.yml文件路由定义里增加no_cache: 'TRUE'可禁用缓存

registration_system.form:
  path: /registration/form
  defaults:
    _form: \Drupal\registration_system\Form\RegistrationForm
  requirements:
    _access: 'TRUE'
  options:
    no_cache: 'TRUE'

也可以在Form的结尾处运行(这一句的影响范围不明确,性能上肯定低于在路由里定义不使用缓存):

\Drupal::service('page_cache_kill_switch')->trigger();

3. 基于用户的缓存(cache contexts)

$build = [
  '#markup' => t('Hi, %name, welcome back to @site!', [
    '%name' => $current_user->getUsername(), 
    '@site' => $config->get('name'), 
  ]),
  '#cache' => [
    'contexts' => [ 
      // The "current user" is used above, which depends on the request, 
      // so we tell Drupal to vary by the 'user' cache context.
      'user', 
    ],
  ], 
];

除了user外,还可以指定更具体的context,例如用户角色,详见:https://www.drupal.org/docs/8/api/cache-api/cache-contexts

4. 清除站点所有缓存

drupal_flush_all_caches();

5. 清除指定用户的缓存


$build = [
     '#markup' => Markup::create($html),
     '#cache' => [
       'contexts' => [
         'user',
       ],
       'tags' => [
         CdcProvider::MENU_BLOCK_TAG, 
         'user:' . \Drupal::currentUser()->id()
       ],
     ],
   ];

// 清除用户缓存
Cache::invalidateTags(['user:' . \Drupal::currentUser()->id()]);
 

参考:https://www.drupal.org/docs/8/api/cache-api/cache-api 

标签

评论

Restricted HTML

  • 允许的HTML标签:<a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id> <img src>
  • 自动断行和分段。
  • 网页和电子邮件地址自动转换为链接。
验证码
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
请输入"Drupal10"