Basic Usage
Last updated Apr 12th, 2019 | Page history | Improve this page | Report an issue
Support the team building MODX with a monthly donation.
The budget raised through OpenCollective is transparent, including payouts, and any contributor can apply to be paid for their work on MODX.
Backers
Budget
$194 per month—let's make that $500!
Learn moreCreate the Snippets¶
Snippet One: Write to Cache¶
Create a Snippet named writeCache:
$cacheManager = $modx->getCacheManager();
$x = date('H:i:s');
$cacheManager->set('my_cache_key',$x);
return $x;
set() takes its second argument by reference. A literal — $cacheManager->set('my_cache_key', date('H:i:s')) — is a fatal error in PHP, so the timestamp goes into $x first.
Put the Snippet on a cacheable Resource, e.g. "Page One":
[[writeCache]]
Snippet Two: Read from Cache¶
Create a Snippet named readCache:
$cacheManager = $modx->getCacheManager();
return $cacheManager->get('my_cache_key');
Put this Snippet on a different Resource, one that is not cacheable, e.g. "Page Two":
[[!readCache]]
Observing the Snippets¶
- Open "Page One". You will see a timestamp, e.g. '11:44:55'.
- Open "Page Two" in another browser tab. It shows the same timestamp, and keeps showing it — waiting does not change it.
Now clear the site cache (Content /-> Clear Cache) and open both Resources again.
The timestamp is written only on the first visit to "Page One" after the clear; the second visit is served from the Resource cache.
Clear the site cache again, then open "Page Two" without visiting "Page One" first.
readCache returns nothing: the cache is empty and writeCache has not run since the cache was cleared.
Now call writeCache uncached:
[[!writeCache]]
- Open "Page One". The timestamp changes on every request.
- Open "Page Two". It shows the timestamp from the last request to "Page One" — the cached value, unchanged by the uncached call.
Summary¶
Both Snippets write to and read from the default partition, so their data is cleared together with the site cache (Content /-> Clear Cache). A Snippet that owns its output this way needs no caching partition of its own.
To keep cached data past a site cache clear, and to let it expire on its own, see Lifetimes.
Support the team building MODX with a monthly donation.
The budget raised through OpenCollective is transparent, including payouts, and any contributor can apply to be paid for their work on MODX.
Backers
Budget
$194 per month—let's make that $500!
Learn more










