描述如何为自定义区块添加缓存标签以便精准清除
解读
在国内大型企业级 Drupal 项目中,区块(Block)往往承载首页焦点图、推荐位、广告位等高频更新内容。若缓存标签设计不当,会导致“全站缓存失效”或“内容更新延迟”,直接引发运营投诉。面试官通过此题考察候选人是否理解 Drupal 8/9/10 的缓存标签(Cache Tags)机制、是否能在插件化开发中正确声明与触发清除,以及是否具备与运维、测试协同的“灰度清除”思维。
知识点
- 缓存标签语义:Drupal 中标签格式为
config:system.menu.main、node:123、block_view:custom_featured等,用于实现“节点级”精准清除。 - 插件类型:自定义区块需继承
Drupal\Core\Block\BlockBase,并重写build()与getCacheTags()。 - 上下文与键:若区块内容依赖用户权限或 URL,需同时实现
getCacheContexts()与getCacheMaxAge(),否则标签会失效。 - 清除时机:通过
Cache::invalidateTags()在实体钩子(如node_update、taxonomy_term_update)或自定义事件订阅器中触发。 - 国内合规:政府与金融项目要求“先清除 CDN 边缘节点,再清除 Drupal 内部缓存”,需结合阿里云、腾讯云 API 做二次封装,避免直接
drush cr造成雪崩。
答案
步骤一:创建插件文件
在自定义模块 custom_demo/src/Plugin/Block/FeaturedBlock.php 中声明:
namespace Drupal\custom_demo\Plugin\Block;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Cache\Cache;
/**
* @Block(
* id = "custom_featured",
* admin_label = @Translation("首页推荐位")
* )
*/
class FeaturedBlock extends BlockBase {
public function build() {
$nids = \Drupal::entityQuery('node')
->condition('type', 'article')
->condition('field_is_featured', 1)
->range(0, 5)
->accessCheck(TRUE)
->execute();
$nodes = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($nids);
$items = [];
foreach ($nodes as $node) {
$items[] = [
'#theme' => 'featured_item',
'#node' => $node,
];
}
return [
'#items' => $items,
'#cache' => [
'tags' => $this->getCacheTags(),
'contexts' => ['user.permissions'],
'max-age' => 3600,
],
];
}
public function getCacheTags() {
// 只要任意一篇 featured 文章变更,区块即失效
return ['custom_featured_list'];
}
public function getCacheContexts() {
return ['user.permissions'];
}
}
步骤二:在节点更新时精准清除
在 custom_demo.module 中实现:
use Drupal\Core\Cache\Cache;
function custom_demo_node_update(\Drupal\node\NodeInterface $node) {
if ($node->bundle() === 'article' && $node->get('field_is_featured')->value) {
Cache::invalidateTags(['custom_featured_list']);
// 国内云厂商 CDN 刷新示例
if (function_exists('aliyun_cdn_flush')) {
aliyun_cdn_flush(['/']);
}
}
}
步骤三:配置管理同步
将区块实例通过 drush config-export 纳入 Git,确保标签 custom_featured_list 在测试、预发、生产环境一致,避免“标签漂移”导致清除失败。
拓展思考
- 多语言场景:若推荐位需按语言隔离,可在
getCacheTags()中追加config:config.language.' . \Drupal::languageManager()->getCurrentLanguage()->getId(),实现“中文更新只清中文首页”。 - 动态标签:当区块内容依赖“当前用户所属部门”时,可在
getCacheTags()中返回['custom_featured_list', 'user_department:' . $user->get('field_department')->target_id],并在部门数据变更时触发Cache::invalidateTags(['user_department:123']),实现“千人千面”级精准清除。 - 灰度策略:国内头部客户常要求“按业务线灰度”。可在标签中加入
custom_featured_list:business_a,并在 CDN 侧配置“标签黑名单”,实现“业务 A 更新只清业务 A 边缘节点”,降低全站回源率。