Drupal 9 当前 IP 地址在不清除缓存的情况下不会改变

问题描述 投票:0回答:1

我创建了一个带有公开下拉列表的视图,其中默认公开值将根据当前国家/地区进行更改。我有一个 api,它可以根据 IP 地址获取当前国家/地区,并且工作绝对完美。

我正在使用VPN来更改当前的IP地址,并且根据IP地址,默认公开的值正在被更改,但问题是,只有在清除缓存后才能正常工作。

我尝试使用下面的代码禁用该部分节点的缓存,但它仍然不起作用。

function MYMODULE_node_view(array &$build, NodeInterface $node, $display, $view_mode) {
  if($node->id()==144) {
    $build['#cache']['max-age'] = 0;
   \Drupal::service('page_cache_kill_switch')->trigger();
  }

完整代码如下所示:

function MYMODULE_views_pre_build(ViewExecutable $view) {
  if(($view->id() === 'myview_id') && ($view->current_display === 'block_1')) {
    $exposed_input = $view->getExposedInput();
    $currentIP = $_SERVER['REMOTE_ADDR'];
    $ipdat = json_decode(file_get_contents("http://www.geoplugin.net/json.gp?ip=" . $currentIP));

    $currentCountry = $ipdat->geoplugin_countryName;

    if($currentCountry=='India') {
      $defaultCountryCode = 26;
      $exposed_input['field_myfield_target_id'] = $defaultCountryCode;
      $view->setExposedInput($exposed_input);
    }
    elseif($currentCountry=='Russia') {
      $defaultCountryCode = 174;
      $exposed_input['field_myfield_target_id'] = $defaultCountryCode;
      $view->setExposedInput($exposed_input);
    }
    else {
      $defaultCountryCode = 26;
      $exposed_input['field_product_geography_area_target_id'] = $defaultCountryCode;
      $view->setExposedInput($exposed_input);
    }
  }
}

我的应用程序如何在不清除缓存的情况下捕获当前 IP 地址?预先感谢。

caching drupal drupal-views drupal-9 drupal-exposed-filter
1个回答
0
投票

视图也有缓存。请检查您的视图缓存配置。

如果您想深入了解并进一步优化

您可以检查https://www.drupal.org/docs/drupal-apis/cache-api/cache-contexts并且您可以使用ip缓存上下文

如果您想深入了解并进一步优化

您可以创建一个国家/地区缓存上下文插件每个国家/地区缓存而不是IP。这是exact示例:https://github.com/drupalcommerce/commerce/blob/8.x-2.x/src/Cache/Context/CountryCacheContext.php

附加重要注意:在缓存上下文插件中使用第三方API是一个非常糟糕的主意并且不可持续。我建议您使用 https://www.php.net/geoip 或至少另外缓存您的 API 结果。

问候,

© www.soinside.com 2019 - 2024. All rights reserved.