Cache api response data for a virtual page programatically

Hi all,

I’ve got a site where I’m using a page model to create a set of virtual pages based on content from an api. The set of pages doesn’t change frequently but still needs to be flexible enough to include new data added to the api response hence I’m using virtual pages.

Each virtual page does another api request on page load. I would like to cache the data being returned but don’t know how I can setup custom caches programmatically. I only know the manual way of defining it inside the config.php file but since the virtual pages can change, I would like not having to do this. I also don’t want to set the cache on the page modal level since the additional api call is quite heavy and would lead to a long page load each time the cache has expired.

So ideally, I would like to archive something like this where a cache is setup with the page uuid in its name e.g. pa5SnIn6WSUzFoRH.

What’s the best way to archive this?

somewhat related post: Check if virtual page exists since it shows code of how to query an api and store that in a cache

I know how to store the data in a cache, but what I don’t know is how I can create a custom cache for each page programmatically without having to define it in the config file manually.

To give a little more insight. Each page loops through subdirectories of a given path on a filesystem and reads a xml which contains some data I extract. This can sometimes be only a few subdirectories but also add up into the hundreds. So having a cache for that data for each page would help a lot in terms of page load/speed.

I don’t see how the post you referred to would help I’m afraid. Unless I’m again missing something obvious with my amateur eyes. :smile:

EDIT: I should add that I don’t want to cache the entire page itself as there is data stored in fields which updates frequently.

  • you create a custom cache via config or plugin
  • in your models you create a getOrSet cache call this only execute if needed and set a key using the models id. that way you create a lot and per model instead of many. $cache->getOrSet() | Kirby CMS

in the model

$cache = kirby()->cache('nameOfYourCache');
$data = $cache->getOrSet('partialCacheFor' . $this->slug(), function() {
   // $this will be page as well
   // find data and return
  return $dataFromXML;
}, 5); // 5 minutes

1 Like

Thanks @bnomei

I do have it working now. I didn’t know that when I set/get the cache Kirby creates different .cache files below the custom cache name/directory.

I just simply do this now in the page controller.

$cache = kirby()->cache('xmlcontent');
$content = $cache->getOrSet($page->slug(), function() use ($nas, $hostname, $basepath) {
    $content = $nas->getContent($hostname, $basepath);
    return $content;
}, 30);