2

Is there a hook or event I can tie into before a page gets cached. I need a hook/event that I can call so that I can run some logic on the page that is about to be cached to tell Drupal if I want a particular page to actually get cached. This is a very specific use case to the website I'm working on.

2

If you need to decide whenever a page should be cached from Drupal, you need to create a service that implements the \Drupal\Core\PageCache\ResponsePolicyInterface interface and it's tagged page_cache_response_policy, as described in Flexible page cache policy.

That page shows code that can be used as example. You can also use code that Drupal core actually implements, as example, like the code for the node.page_cache_response_policy.deny_node_preview service.

The code implementing the service is quite simple. It becomes more complex basing on the logic you need to apply to decide when a page should be cached.

class DenyNodePreview implements ResponsePolicyInterface {

  /**
   * The current route match.
   *
   * @var \Drupal\Core\Routing\RouteMatchInterface
   */
  protected $routeMatch;

  /**
   * Constructs a deny node preview page cache policy.
   *
   * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
   *   The current route match.
   */
  public function __construct(RouteMatchInterface $route_match) {
    $this->routeMatch = $route_match;
  }

  /**
   * {@inheritdoc}
   */
  public function check(Response $response, Request $request) {
    if ($this->routeMatch
      ->getRouteName() === 'entity.node.preview') {
      return static::DENY;
    }
  }

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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