Sometimes you have large amount of generated data that you don’t want to create on every web request.
An examples would be a home page with several news posts on it.
The text would be in a database, but all the ‘extra’ things you did like bbtags present in the text, information about the user that posted it, etc etc requires extra processing.
If these queries and calculation only have to be done once then it would mean a big performance gain. Especially if it’s on pages that get requested allot.
The solution for this is shared memory. APC has this, if you do not know what APC is, please read this blog post about opcode cachers.
So, we have data and we want to store it in memory, what we need is a small wrapper class that does all the work for us, explanation is in the code:
<?php /** * Contains the APCCache class to store, retrieve and delete data from the APC shared memory * @package Tools * @author Crazy <crazytje@gmail.com> * @copyright 2000-2010 Crazy * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @filesource * @link http://www.php.net/manual/en/book.apc.php */ /** * used to store, retrieve and delete data from the APC shared memory * * @package Tools * @author Crazy <crazytje@gmail.com> * @copyright 2000-2010 Crazy * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @link http://www.php.net/manual/en/book.apc.php */ class APCCache { /** * Contains the prefix that will be prepended to the identifiers * @var string */ private static $prefix = 'MyPrefix'; /** * Stores a variable in the shared memory * * @param string $pKey Unique identifier for the data * @param mixed $pValue Data to store * */ public static function SetVar($pKey, $pValue) { return apc_store(self::$prefix.'.'.$pKey, $pValue); } /** * Returns a stored variable from the shared memory * * @param string Data identifier * * @return mixed stored data * */ public static function GetVar($pKey) { return apc_fetch(self::$prefix.'.'.$pKey); } /** * Removed data from the shared memory * * @param string Data identifier * */ public static function Destroy($pKey) { return apc_delete(self::$prefix.'.'.$pKey); } /** * Sets a prefix for your identifiers * This is to prevent conflicts with software also using apc * * @param string $pValue prefix */ public static SetPrefix($pValue) { self::$prefix = $pValue; } } ?>
Example usage:
<?php APCCache::SetVar('MyTest', 'wOOt'); $var = APCCache::GetVar('MyTest'); //outputs 'MyTest' echo $var; ?>
Easy right?
