【发布时间】:2019-06-15 05:13:14
【问题描述】:
我有以下情况:我想根据当前用户的某个字段隐藏或显示一些本地任务(选项卡)。因此我实现了hook_menu_local_tasks_alter() in my_module/my_module.module:
function my_module_menu_local_tasks_alter(&$data, $route_name, \Drupal\Core\Cache\RefinableCacheableDependencyInterface &$cacheability) {
... some logic ...
if ($user->get('field_my_field')->getValue() === 'some value')
unset($data['tabs'][0]['unwanted_tab_0']);
unset($data['tabs'][0]['unwanted_tab_1']);
... some logic ...
}
这很好,但如果field_my_field 的值发生变化,我需要清除缓存。
所以我发现我需要在我的my_module_menu_local_tasks_alter 中实现这样的缓存上下文:
$cacheability
->addCacheTags([
'user.available_regions',
]);
我已经这样定义了我的缓存上下文:
my_module/my_module.services.yml:
services:
cache_context.user.available_regions:
class: Drupal\my_module\CacheContext\AvailableRegions
arguments: ['@current_user']
tags:
- { name: cache.context }
my_module/src/CacheCotext/AvailableRegions.php:
<?php
namespace Drupal\content_sharing\CacheContext;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Cache\Context\CacheContextInterface;
use Drupal\Core\Session\AccountProxyInterface;
/**
* Class AvailableRegions.
*/
class AvailableRegions implements CacheContextInterface {
protected $currentUser;
/**
* Constructs a new DefaultCacheContext object.
*/
public function __construct(AccountProxyInterface $current_user) {
$this->currentUser = $current_user;
}
/**
* {@inheritdoc}
*/
public static function getLabel() {
return t('Available sub pages.');
}
/**
* {@inheritdoc}
*/
public function getContext() {
// Actual logic of context variation will lie here.
$field_published_sites = $this->get('field_published_sites')->getValue();
$sites = [];
foreach ($field_published_sites as $site) {
$sites[] = $site['target_id'];
}
return implode('|', $sites);
}
/**
* {@inheritdoc}
*/
public function getCacheableMetadata() {
return new CacheableMetadata();
}
}
但是每次我更改我的字段field_my_field 的值时,我仍然需要清除缓存,因此上下文不起作用。谁能指出我正确的方向如何解决这个问题或如何调试这种事情?
【问题讨论】: