Adding memcached to the Mix
The following is all that is required to cache your latest headlines with memcached.
<?php
/* import the memcached client library */
loader_import ('myapp.MemCachedClient');
/* initialize your memcached client object */
$memcached = new MemCachedClient ();
$memcached->set_servers (array ('127.0.0.1:11211'));
/* try to retrieve the headlines from memcached */
$out = $memcached->get ('myapp:latestheadlines');
if (! $out) {
/* retrieve the top 10 headlines */
$res = db_fetch_array (
'select id, title from sitellite_news
order by date desc limit 10'
);
/* display the headlines as a bulleted list */
$out = template_simple (
'<h2>{intl Latest Headlines}</h2>
<ul>
{loop obj}
<li>
<a href="{site/prefix}/index/tutorials-story-action/story.{loop/id}">
{loop/title}
</a>
</li>
{end loop}
</ul>',
$res
);
/* store the headlines in memcached for next time,
* renewing every 5 minutes (300 seconds)
*/
$memcached->set ('myapp:latestheadlines', $out, time () + 300);
}
echo $out;
?>
The core of the memcached functionality is in the get() and set()
lines, but the logical structure of the changed code is also
important. The logical structure of a memcached request is as
follows. First, we import the memcached client API and create the
client object:
<?php
/* import the memcached client library */
loader_import ('myapp.MemCachedClient');
/* initialize your memcached client object */
$memcached = new MemCachedClient ();
$memcached->set_servers (array ('127.0.0.1:11211'));
?>
Next, we check memcached for the cached copy:
<?php
/* try to retrieve the headlines from memcached */
$out = $memcached->get ('myapp:latestheadlines');
?>
But if it's not available, we generate our content as we normally would:
<?php
if (! $out) {
/* retrieve the top 10 headlines */
$res = db_fetch_array (
'select id, title from sitellite_news
order by date desc limit 10'
);
/* display the headlines as a bulleted list */
$out = template_simple (
'<h2>{intl Latest Headlines}</h2>
<ul>
{loop obj}
<li>
<a href="{site/prefix}/index/tutorials-story-action/story.{loop/id}">
{loop/title}
</a>
</li>
{end loop}
</ul>',
$res
);
?>
Then we store the newly created copy in memcached, so that it will be available on the next page request:
<?php
/* store the headlines in memcached for next time,
* renewing every 5 minutes (300 seconds)
*/
$memcached->set ('myapp:latestheadlines', $out, time () + 300);
?>
Then finally, we output the results, which are identical whether they came from your custom code or memcached:
<?php
echo $out;
?>
Conclusion
That's all there is to it. So you can see that in just a few
lines of code, you can easily add that extra boost of performance
needed by those repetitively queried portions of the web site that
don't need to be unique and real-time ready for each unique visitor.
Page 1: Installing memcached
Page 2: Running memcached
Page 3: Adding memcached to the Mix
All Tutorials