Jump to content

Question about $cache->preload()


Robin S
 Share

Recommended Posts

I have a piece of expensive code/markupthat I am caching using WireCache. I have a Pages::save hook for pages of a particular template where I clear the cache to account for the changes.

$this->cache->delete('my-cache-name');

In that hook, after the cache is cleared I want to regenerate the cache, so the expensive code is run then rather than when a page is viewed on the front-end. I thought that this would do that...

$this->cache->preload(['my-cache-name']);

...but based on the execution time of the next page view on the front-end, which I'm tracking with Debug::timer(), it seems like the cache has not been regenerated in advance.

Is this what $cache->preload() is for? i.e. regenerating a cache ahead of time so it is ready to go when called for. And is there some trick to using it that I'm missing?

Link to comment
Share on other sites

5 hours ago, Robin S said:

Is this what $cache->preload() is for? i.e. regenerating a cache ahead of time so it is ready to go when called for

It's not for regeneration, but reading caches from DB together (by using preloadFor or by giving an array of cache names) into $cache instance (that was created at boot). This way no further calls are done to DB, they will be served from memory directly.

I hope this part from the core makes it clear

<?php
// /wire/core/WireCache.php

// Preloaded cache values, indexed by cache name
protected $preloads = array();

/**
* Preload the given caches, so that they will be returned without query on the next get() call
* After a preloaded cache is returned from a get() call, it is removed from local storage. */
public function preload(array $names, $expire = null) {
    if(!is_array($names)) $names = array($names);
    $this->preloads = array_merge($this->preloads, $this->get($names, $expire));
}

where $this->get() builds SQL query and fetches caches from database.

So, if you're fetching caches once, it makes no difference to use $cache->get(['name', 'another']) or $cache->preload(['this', 'that']) then $cache->get(), but for multiple calls, it does.

What you should be using to regenerate caches is just calling $cache->save() and it will regenerate and override previous caches.

Edit:
Considering the second sentence of the function documentation, the preloaded caches are flushed from the memory once they are requested with get(), so it's just useful for reducing DB calls to one.

  • Like 3
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...