User:Jeroen De Dauw/CacheHelper

This page documents the CacheHelper and related classes.

Rationale
We often want to cache various elements in interfaces, such as on special pages and actions. Although this is doable with just the existing caching interface (BagOStuff), it involves writing a lot of repetitive code obscuring the actual logic of your interface creating code. The CacheHelper class abstracts this out, and has a number of common needed features build in as well, such as purging on action=purge and displaying a notice that a page is cached.

Implementation

 * CacheHelper: contains all the core logic and can be used pretty much any where where you need to cache a bunch of stuff and would like to do so in batch.
 * ICacheHelper: interface for everything implementing CacheHelper functionality.
 * SpecialCachedPage: SpecialPage holding a CacheHelper and implementing ICacheHelper.
 * CachedAction: FormlessAction holding a CacheHelper and implementing ICacheHelper.

Requirements

 * MediaWiki 1.20, since this code uses the new formatDuration in Language
 * PHP 5.2 or later

Usage
Before using any of the cahing functionality, call startCache. After the last call to either getCachedValue or addCachedHTML, call saveCache.

To get a cached value or compute it, use getCachedValue like this

To add HTML that should be cached, use addCachedHTML like this

The callback function is only called when needed, so do all your expensive computations here. In case of getCachedValue, the value is returned, in case of addCachedHTML, the HTML is added to the OutputPage of the Action or SpecialPage.