Jump to content

Caching pages doesn't executes with external param


Jimbos
 Share

Recommended Posts

Hello, I'm trying to cache some queries. Everything works correctly, but I encounter issues when I try to insert one or more external variables into the function:

$name = $cache->get('cachedname', "+2 minutes", function($pages) { 
    return $pages->find("template=names, parent=1195, id=$nameid, status=published, limit=3");
}); 

Can you help me?

Link to comment
Share on other sites

I would assume the $nameid variable is not available in your closure unless you add use ($nameid) to include it. $pages is available only because WireCache supports optionally passing API variables as arguments.

This should work:

$name = $cache->get('cachedname', "+2 minutes", function($pages) use($nameid) { 
    return $pages->find("template=names, parent=1195, id=$nameid, status=published, limit=3");
}); 

Here is some documentation about closures: PHP: Anonymous functions - Manual

Edited by poljpocket
add docs link
  • Like 1
Link to comment
Share on other sites

Also, your cache function only works as expected if the $nameid variable is the same every time you use a cached version of the query. To get around this, you should make the cache key depend on it, e.g.:

$name = $cache->get("cachedname-$nameid", "+2 minutes", function($pages) use($nameid) { 
    return $pages->find("template=names, parent=1195, id=$nameid, status=published, limit=3");
});

 

  • Like 2
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...