0

I am invalidating a cache tag in KernelEvents::REQUEST event:

public static function getSubscribedEvents() {
  $events[KernelEvents::REQUEST][] = ['onRequest', 100];
  return $events;
}
public function onRequest(GetResponseEvent $event) {
  if ($this->request->cookies->has('myValue')) {
    $this->cacheTagsInvalidator->invalidateTags(['my_tag']);
  }
}

When I refresh the page the tag is invalidated but the changes are showing on the next refresh, to which event/hook/etc. do I need to subscribe me to see my changes in single refresh ?

Edit 1: I have 'Internal Page Cache' module installed. If I uninstall it, the code above works fine.

Edit 2: Added the if condition.

8
  • You would need a middleware, see drupal.stackexchange.com/questions/287393/…. But what is in (...) that you need to do this?
    – 4uk4
    Commented Nov 20, 2019 at 21:28
  • (...) is a simple condition, my issue is that the code in onRequest function executes to late.
    – rpayanm
    Commented Nov 21, 2019 at 13:26
  • Yes, this is why you need a middleware, because the internal page cache is executed outside of DrupalKernel. But if this is only a simple condition there should be an easier solution, normally you don't invalidate cache tags like this.
    – 4uk4
    Commented Nov 21, 2019 at 13:34
  • I edit my question and added the condition. I need check if a value is in cookie, if is TRUE, I invalidate a tag for re-render a block.
    – rpayanm
    Commented Nov 21, 2019 at 13:42
  • The condition makes no sense because you have no way back for a response without cookie value. You need a cache context for the cookie and disable page caching for pages where the block is displayed.
    – 4uk4
    Commented Nov 21, 2019 at 14:29

1 Answer 1

0

I did it implementing a middleware:

mymodule/mymodule.services.yml:

mymodule.http_middleware:
  class: Drupal\mymodule\StackMiddleware\BeforePageCache
  arguments:
    - '@cache_tags.invalidator'
  tags:
    - { name: http_middleware, priority: 280, responder: true }

mymodule/src/StackMiddleware/BeforePageCache.php

...
/**
 * {@inheritdoc}
 */
public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = TRUE) {
  if ($request->cookies->has('myValue')) {
    $this->cacheTagsInvalidator->invalidateTags(['my_tag']);
  }

  return $this->httpKernel->handle($request, $type, $catch);
}
...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.