Caching data for the duration of one request (custom kirbytag)

I have a custom kirbytag that may be called dozens of times while rendering one page (a custom implementation of the (link:) kirbytag, with some magic sprinkled on). Among other things, I am loading an array from a file that is needed for rendering the kirbytag’s output.

How would I go about to “cache” the array data from that file in RAM so the file is not read multiple times while rendering that single page? This is probably totally obvious, but my Friday brain doesn’t want to cooperate… Thank you!

Edit: I just realized, another plugin with another kirbytag actually also needs that array. So I’m really looking for some kind of “global” place to safekeep that data for the duration of the request.

You could create a small data provider class with a static property that only fetches the data from file if it’s null.

1 Like

Sweet, that works like a charm! Thank you.

In case anybody ever needs something like this, here’s a template:

// index.php (of my plugin)
    'my\\Plugin\\DataProvider' => 'classes/DataProvider.php',
], __DIR__);
Kirby::plugin('my/plugin', [
    // the rest of the plugin; kirbytags config etc.
// classes/DataProvider.php
namespace My\Plugin;
use Kirby\Data\Json;
class DataProvider {
    private static $deadLinks = null;
    public static function deadLinks() {
        if (!self::$deadLinks) {
            self::$deadLinks = Json::read(kirby()->root('logs') . '/dead-links.json');
        return self::$deadLinks;

In my custom kirbytag, I can call $deadlinks = My\Plugin\DataProvider::deadlinks(); and now get the array from the file, but cached in the static property :slight_smile: