Two recent sites I’ve built have plugins built to handle filtering through projects based on some categories and related entries.

For example the lookups look similar to this:

# Get element criterea for searching projects
$projectCriterea = craft()->elements->getCriteria(ElementType::Entry);
$projectCriterea->section = 'projects';
$projectCriterea->limit = null;
$projectCriterea->relatedTo = $relatedElements; # This is an array of categories and related entries.
$projects = $projectCriterea->find();

All these lookups aren’t particularly fast, and there aren’t that many different variants. Is there a way I can add some caching into these lookups?

I had a bit of a look into the CacheService but I'm not sure how to apply that to this.



I have figured it out, but am not sure if this is the best way so could still use some advice.

# Get a unique hash of your search criteria (still figuring this out).
$hash = md5(json_encode($projectCriterea));

# Look up the cache
$cache = craft()->cache->get($hash);

# Did we find this search criterea in the cache already? If so, return it.
if ($cache) {
    return $cache;

# No cache? Do searchy business
# ...
$projects = $projectCriterea->find();
# ...

# Save to the cache
if ($cache === false) {
    craft()->cache->set($hash, $projects, 604800); # Cache for 1 week

return $projects;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.