Caching

From SMFMods

Jump to: navigation, search

SMF has in-built caching support, which may be activated via the Server Settings section of the admin panel. SMF supports APC, eAccelerator, Turck MMCache, Memcached, Zend Platform, and Xcache (with a patch). Additionally, SMF 2.0 also supports a flat-file cache.

[edit] Writing data to the cache

Data is written to the cache using the cache_put_data function. The syntax for this command is:
cache_put_data(key, value, ttl);

  • key — A key to store the value under. You use the key to retrieve the data later.
  • value — The data itself.
  • ttl — Time to live. This is how long the data will be cached for, in seconds. After this time interval is up, the cached data will be deleted.

[edit] Reading data from the cache

Similarly, reading data from the cache is done using the cache_get_data function. The syntax for this command is:
cache_get_data(key, ttl);
With the key and ttl parameters having the same meaning as for cache_put_data.

[edit] Example code

Usually, the caching functions are used in conjunction with a database query. If the data is cached, then use the cached data. Otherwise, run the query and store the data in the cache. This can be done like so:

// Try to get the data from the cache.
if (($row == cache_get_data('test', 120)) == null)
{
	// If it failed (ie. not cached), we perform the query like usual.
	$result = db_query("
		SELECT realName
		FROM {$db_prefix}members
		WHERE ID_MEMBER = 1", __FILE__, __LINE__);
	$row = mysql_fetch_assoc($request);
	mysql_free_result($request);
 
	// Store this data in the cache.
	cache_put_data('test', $row, 120);
}
 
// At this point, $row will contain the data we need.
Personal tools