Caching in Single pages

Couldn’t find any answer if this is by now finally possible: Can single pages be cached depending on their parameters.

Eg. /hotel/hotelname1 gets a different cache than /hotel/hotelname2.

Possible out of the box or only with my own implementation?

Yes you can cache specific pages by going to page properties and setting the caching options for the page manually.

Hi Evan. Thank you, but that would mean I need to add and change hundreds of changing entries, while it should be possible to say to just cache any parameter of a single page on its own.

I made an own implementation now. That seems to work fine.

1 Like

Awesome, sounds good! Just a note that you can also change properties in bulk in the page search. But it sounds like you’ve got it handled. :+1:

If anyone else needs it:

// Check if the user is registered and whether caching for registered users is allowed
if ($this->checkIsRegisteredUser() && !$this->btCacheBlockOutputForRegisteredUsers) {
    // For users who don't meet caching criteria, generate content dynamically
    $content = $this->generateDynamicContent($parameters);
} else {
    // Generate a cache key based on id of the url and active language
    $cacheKey = Localization::activeLanguage() . '_hotel_' . md5($url_name);
    $timestampCacheKey = $cacheKey . '_timestamp';

    // Fetch the cache service
    $cache = $this->app->make('cache/expensive');
    $cachedContent = $cache->getItem($cacheKey);
    $timestampItem = $cache->getItem($timestampCacheKey);

    $refreshCache = false;

    if ($timestampItem->isHit()) {
        $lastCacheTime = $timestampItem->get();
        $currentTime = time();

        // Check if the cache has expired based on the last cache time and the defined lifetime
        if (($currentTime - $lastCacheTime) >= $this->singlePageCacheLifetime) {
            $refreshCache = true;
        }
    } else {
        $refreshCache = true; // No timestamp means we need to refresh the cache
    }

    if (!$cachedContent->isHit() || $refreshCache) {
        // Cache miss or cache needs to be refreshed: Generate dynamic content
        $content = $this->generateDynamicContent($parameters);
        
        // Store the generated content in the cache with the specified lifetime
        $cachedContent->set($content);
        $cachedContent->expiresAfter($this->singlePageCacheLifetime);
        $cache->save($cachedContent);

        // Update the timestamp of when the content was cached
        $timestampItem->set(time());
        $cache->save($timestampItem);
    } else {
        // Cache hit: Retrieve cached content
        $content = $cachedContent->get();
    }
}
1 Like