Kirby3 Lapse - Cache any data until set expiration time (with automatic keys)

I am creating posts for my plugins to make it easier to find them using the forum search and not just the docs search.

Cache any data until set expiration time (with automatic keys).

Usecase

The Kirby Pages-Cache can cache the output of Page Templates. It devalidates all cache files if any Object in the Panel is changed. This is a good choice if you do not make changes often. But if you do make changes often you need a cache that knows what has been modified and which caches to devalidate and which not.

Sometimes you can not cache the complete Page since…

  • it contains a form with a csrf hash,
  • you use content security headers with nouces,
  • build and cache data for a logicless templating system like handlebars or
  • you want to cache data from an external source like an API.

Lapse was build to do exactly that: Cache any data until set expiration time.

// lapse v1 could already do this:
// store data until objects are modified with optional expire
$data = Lapse::io(
    $page->id().$page->modified(),
    ['some', 'kind', 'of', 'data'],
    60*24*7 // one week
);

// now it can create magic cache keys from kirby objects
$data = Bnomei\Lapse::io(
    $page, // key with modification date created by lapse based on object 
    function () use ($page) {
        return [
           'title' => $page->title(),
       ];
    }
);

// or from an collection of pages or files
$collection = collection('mycollection');
$data = Lapse::io(
    $collection, // this will turn into a key taking modification date of all objects into consideration
    function () use ($collection) {
        return [ /*...*/ ];
    }
);

// or from an array combining all these
$data = Lapse::io(
    ['myhash', $page, $page->children()->images(), $collection, $site], // will create key from array of objects
    function () use ($site, $page, $collection) {
        return [
            // will not break serialization => automatically store ->value() of fields
            'author' => $site->author(),
            'title' => $page->title(),
            'hero' => $page->children()->images()->first()->srcset()->html(),
            'count' => $collection->count(),
        ];
    }
);

// BONUS: if you use autoid or boost the modified lookups will be at almost zero-cpu cost.