1

I have a plugin that renders HTML via a hook. If someone wraps that hook with {% cache %} in their templates, how can my plugin tell Craft to invalidate the cache when something within it changes?

EDIT: Let's say, for example, that I'm getting JSON data from an external source via my plugin. I could be rendering this via a hook, or using a Variable, it doesn't matter that much.

There's no Element that the content that changes can be linked to, in order to invalidate the cache.

  • Can you give an example of a template using your plugin? Also, it'd be helpful if you could describe the HTML rendered by your plugin – what does it contain and what "changes" in it when you want to break the cache? – Mats Mikkel Rummelhoff Jan 18 '16 at 10:10
2

The TemplateCacheService provides a ton of helpful methods to take care of this for you.

While you can explicitly tell Craft to invalidate certain caches (by element ID, etc.) if you need to, I prefer to use includeCriteriaInTemplateCaches() and includeElementInTemplateCaches() to register the appropriate element(s)/criteria with the template cache, so that Craft takes care of cache invalidation according to its own internal logic:

$myCrtieria = ... ; // (some ElementCriteriaModel)

$cacheService = craft()->getComponent('templateCache', false);

if ($cacheService)
{
    $cacheService->includeCriteriaInTemplateCaches($myCriteria);
}  

...

p.s. Unless you really need to render HTML via a Twig hook, I strongly suggest refactoring to use a custom Template Variable instead. Doing so is more consistent with Craft's own internal practice. Twig hooks are typically used to change context variables and perform other logic that is specific to changing how Twig renders templates. For doing content-related business logic (e.g. fetching data from the database and rendering it into templates), using Craft's provided structures will save you trouble down the road.

|improve this answer|||||
  • I'm aware of these methods... I have no Criteria or Element, though. – andrew.welch Jan 19 '16 at 11:19
  • Ah, I see. By what event/criteria do you judge that the underlying info has changed and you ought to break the cache? – Michael Rog Jan 19 '16 at 15:38
  • In this, via a hash of the data. I'm just looking for a generalized way to tell Craft that a cache needs to be broken... but I'm guessing the only way to do it would be to make a fake element for the express purpose of cache busting. – andrew.welch Jan 19 '16 at 18:36
  • 1
    That would be the approach I'd take: To create a custom Element Type and manage it through your plugin. – Michael Rog Jan 19 '16 at 22:52

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.