3 * Cache of various elements in a single cache entry.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @license GNU GPL v2 or later
22 * @author Jeroen De Dauw < jeroendedauw@gmail.com >
26 * Interface for all classes implementing CacheHelper functionality.
30 interface ICacheHelper
{
33 * Sets if the cache should be enabled or not.
36 * @param boolean $cacheEnabled
38 function setCacheEnabled( $cacheEnabled );
41 * Initializes the caching.
42 * Should be called before the first time anything is added via addCachedHTML.
46 * @param integer|null $cacheExpiry Sets the cache expiry, either ttl in seconds or unix timestamp.
47 * @param boolean|null $cacheEnabled Sets if the cache should be enabled or not.
49 function startCache( $cacheExpiry = null, $cacheEnabled = null );
52 * Get a cached value if available or compute it if not and then cache it if possible.
53 * The provided $computeFunction is only called when the computation needs to happen
54 * and should return a result value. $args are arguments that will be passed to the
55 * compute function when called.
59 * @param {function} $computeFunction
60 * @param array|mixed $args
61 * @param string|null $key
65 function getCachedValue( $computeFunction, $args = array(), $key = null );
68 * Saves the HTML to the cache in case it got recomputed.
69 * Should be called after the last time anything is added via addCachedHTML.
76 * Sets the time to live for the cache, in seconds or a unix timestamp
77 * indicating the point of expiry...
81 * @param integer $cacheExpiry
83 function setExpiry( $cacheExpiry );
88 * Helper class for caching various elements in a single cache entry.
90 * To get a cached value or compute it, use getCachedValue like this:
91 * $this->getCachedValue( $callback );
93 * To add HTML that should be cached, use addCachedHTML like this:
94 * $this->addCachedHTML( $callback );
96 * The callback function is only called when needed, so do all your expensive
97 * computations here. This function should returns the HTML to be cached.
98 * It should not add anything to the PageOutput object!
100 * Before the first addCachedHTML call, you should call $this->startCache();
101 * After adding the last HTML that should be cached, call $this->saveCache();
105 class CacheHelper
implements ICacheHelper
{
108 * The time to live for the cache, in seconds or a unix timestamp indicating the point of expiry.
113 protected $cacheExpiry = 3600;
116 * List of HTML chunks to be cached (if !hasCached) or that where cached (of hasCached).
117 * If not cached already, then the newly computed chunks are added here,
118 * if it as cached already, chunks are removed from this list as they are needed.
123 protected $cachedChunks;
126 * Indicates if the to be cached content was already cached.
127 * Null if this information is not available yet.
132 protected $hasCached = null;
135 * If the cache is enabled or not.
140 protected $cacheEnabled = true;
143 * Function that gets called when initialization is done.
148 protected $onInitHandler = false;
151 * Elements to build a cache key with.
156 protected $cacheKey = array();
159 * Sets if the cache should be enabled or not.
162 * @param boolean $cacheEnabled
164 public function setCacheEnabled( $cacheEnabled ) {
165 $this->cacheEnabled
= $cacheEnabled;
169 * Initializes the caching.
170 * Should be called before the first time anything is added via addCachedHTML.
174 * @param integer|null $cacheExpiry Sets the cache expiry, either ttl in seconds or unix timestamp.
175 * @param boolean|null $cacheEnabled Sets if the cache should be enabled or not.
177 public function startCache( $cacheExpiry = null, $cacheEnabled = null ) {
178 if ( is_null( $this->hasCached
) ) {
179 if ( !is_null( $cacheExpiry ) ) {
180 $this->cacheExpiry
= $cacheExpiry;
183 if ( !is_null( $cacheEnabled ) ) {
184 $this->setCacheEnabled( $cacheEnabled );
187 $this->initCaching();
192 * Returns a message that notifies the user he/she is looking at
193 * a cached version of the page, including a refresh link.
197 * @param IContextSource $context
198 * @param boolean $includePurgeLink
202 public function getCachedNotice( IContextSource
$context, $includePurgeLink = true ) {
203 if ( $this->cacheExpiry
< 86400 * 3650 ) {
204 $message = $context->msg(
205 'cachedspecial-viewing-cached-ttl',
206 $context->getLanguage()->formatDuration( $this->cacheExpiry
)
210 $message = $context->msg(
211 'cachedspecial-viewing-cached-ts'
215 if ( $includePurgeLink ) {
216 $refreshArgs = $context->getRequest()->getQueryValues();
217 unset( $refreshArgs['title'] );
218 $refreshArgs['action'] = 'purge';
220 $subPage = $context->getTitle()->getFullText();
221 $subPage = explode( '/', $subPage, 2 );
222 $subPage = count( $subPage ) > 1 ?
$subPage[1] : false;
224 $message .= ' ' . Linker
::link(
225 $context->getTitle( $subPage ),
226 $context->msg( 'cachedspecial-refresh-now' )->escaped(),
236 * Initializes the caching if not already done so.
237 * Should be called before any of the caching functionality is used.
241 protected function initCaching() {
242 if ( $this->cacheEnabled
&& is_null( $this->hasCached
) ) {
243 $cachedChunks = wfGetCache( CACHE_ANYTHING
)->get( $this->getCacheKeyString() );
245 $this->hasCached
= is_array( $cachedChunks );
246 $this->cachedChunks
= $this->hasCached ?
$cachedChunks : array();
248 if ( $this->onInitHandler
!== false ) {
249 call_user_func( $this->onInitHandler
, $this->hasCached
);
255 * Get a cached value if available or compute it if not and then cache it if possible.
256 * The provided $computeFunction is only called when the computation needs to happen
257 * and should return a result value. $args are arguments that will be passed to the
258 * compute function when called.
262 * @param {function} $computeFunction
263 * @param array|mixed $args
264 * @param string|null $key
268 public function getCachedValue( $computeFunction, $args = array(), $key = null ) {
269 $this->initCaching();
271 if ( $this->cacheEnabled
&& $this->hasCached
) {
274 if ( is_null( $key ) ) {
275 $itemKey = array_keys( array_slice( $this->cachedChunks
, 0, 1 ) );
276 $itemKey = array_shift( $itemKey );
278 if ( !is_integer( $itemKey ) ) {
279 wfWarn( "Attempted to get item with non-numeric key while the next item in the queue has a key ($itemKey) in " . __METHOD__
);
281 elseif ( is_null( $itemKey ) ) {
282 wfWarn( "Attempted to get an item while the queue is empty in " . __METHOD__
);
285 $value = array_shift( $this->cachedChunks
);
289 if ( array_key_exists( $key, $this->cachedChunks
) ) {
290 $value = $this->cachedChunks
[$key];
291 unset( $this->cachedChunks
[$key] );
294 wfWarn( "There is no item with key '$key' in this->cachedChunks in " . __METHOD__
);
299 if ( !is_array( $args ) ) {
300 $args = array( $args );
303 $value = call_user_func_array( $computeFunction, $args );
305 if ( $this->cacheEnabled
) {
306 if ( is_null( $key ) ) {
307 $this->cachedChunks
[] = $value;
310 $this->cachedChunks
[$key] = $value;
319 * Saves the HTML to the cache in case it got recomputed.
320 * Should be called after the last time anything is added via addCachedHTML.
324 public function saveCache() {
325 if ( $this->cacheEnabled
&& $this->hasCached
=== false && !empty( $this->cachedChunks
) ) {
326 wfGetCache( CACHE_ANYTHING
)->set( $this->getCacheKeyString(), $this->cachedChunks
, $this->cacheExpiry
);
331 * Sets the time to live for the cache, in seconds or a unix timestamp
332 * indicating the point of expiry...
336 * @param integer $cacheExpiry
338 public function setExpiry( $cacheExpiry ) {
339 $this->cacheExpiry
= $cacheExpiry;
343 * Returns the cache key to use to cache this page's HTML output.
344 * Is constructed from the special page name and language code.
349 * @throws MWException
351 protected function getCacheKeyString() {
352 if ( $this->cacheKey
=== array() ) {
353 throw new MWException( 'No cache key set, so cannot obtain or save the CacheHelper values.' );
356 return call_user_func_array( 'wfMemcKey', $this->cacheKey
);
360 * Sets the cache key that should be used.
364 * @param array $cacheKey
366 public function setCacheKey( array $cacheKey ) {
367 $this->cacheKey
= $cacheKey;
371 * Rebuild the content, even if it's already cached.
372 * This effectively has the same effect as purging the cache,
373 * since it will be overridden with the new value on the next request.
377 public function rebuildOnDemand() {
378 $this->hasCached
= false;
382 * Sets a function that gets called when initialization of the cache is done.
386 * @param $handlerFunction
388 public function setOnInitializedHandler( $handlerFunction ) {
389 $this->onInitHandler
= $handlerFunction;