Jump to content

caching a query result with $cache


Recommended Posts

Hello guys,

I’d like to dig a little bit in the $cache API.
In my homepage template, I call data from on other page, in repeater field.
Although it has only 16 items, I noticed that it slowed down the loading process.
When I use the cache a template level, the page is definitely faster.
In the homepage template, I do the following :

$consultants = $pages->get(1027)->repeaterConsultants;
foreach ($consultants as $consultant) {
    // do stuff with $consultant->consultantPortrait, $consultant->consultantName, etc...

I tried to put in cache the $consultants variable. I read a tutorial on processwire.dev and I read the docs but I can’t get it working...
The test below work perfectly though.

$test = $cache->get("test", 3600, function(){return "this is a test";});

So how could I cache the $consultants variable?


Link to comment
Share on other sites

@TomPich I wouldn't recommend caching a field value like that, as I don't think you'll get any performance benefit since the amount of work for PW to do is the same either way there. What I'd recommend doing instead is caching the resulting output, which also means only loading the repeaterConsultants when it will be used to generate that cached markup. Whatever markup you generate, use that as your cache value, for example:

echo $cache->get('consultants', 'hourly', function() use($pages) {
  $out = '';
  $consultants = $pages->get(1027)->repeaterConsultants;
  foreach ($consultants as $consultant) {
    $out .= "<li>$consultant->consultantName</li>";
  return "<ul>$out</ul>" ;


  • Like 2
  • Thanks 1
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

  • Recently Browsing   0 members

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