Spent today fiddling with the caching of files in php. Its quite easy to do really, just working out how you would do it is the difficult bit. Some things are easy to cache and some aren't. Not yet got my head around how each individual users information could be cached, but the items that are the same for everyone are good candidates.
My first attempt was the shout box script. Basically every time some visits the jail, hospital or forest scripts, the database is accessed to collect the last 10 messages.
The way the new version works is this. When you enter the script it checks to see if a cached version of the shout box exists, if not it carries onto the database lookup. It gathers the data and creates a cached HTML file of that data.
It is a little more complicated than that, it also checks to see if a message has been added, if so then this will make it recreate the cached file too. To be sure it stays up to date.
Now why would this make a difference, well obviously if someone uses the forest script, they have 250 clicks or more. In the old version that would be accessing the database 250 times. Not good. In the new one, if no one adds a new message to the shoutbox that would be zero database accesses, but even if a few messages are added during a players steps it will save a lot of database traffic. We will see how this effects things.
The code would be something like this...
$CacheFile="somedir/blah.html"; // the html copy of your output to the browser
// we first check to see if the cache file actually exists
if (file_exists($CacheFile))
{
include($CacheFile); // it does so we output that and exit.
exit;
}
ob_start(); // this supresses the html output to the browser
// Here you create the output that you want people to see
// the user will not see it yet
$fp=fopen($CacheFile,'w'); // you now create your output file
fwrite($fp,ob_get_contents()); // here you send the ob content to the file
fclose($fp); // now you close the file to be sure it gets written etc.
ob_end_flush(); // now output to the browser as usuall
Of course you will have to have the appropriate permissions to write the files to the chosen directory etc, but it can be a quite effective way of reducing hits on your database.
Now to look at other scripts to see if this can be added in other places.
Wednesday, May 28, 2008
Caching files
Blogged with the Flock Browser
Posted by
NoobEnforcer
at
Wednesday, May 28, 2008
Labels: caching, database, kingdom of riches, php
Subscribe to:
Post Comments (Atom)

No comments:
Post a Comment