FROST

FRee and Open Source Technologies

PHP Caching using Memcached

Why cached? It's simple, you want speed. How? Say you have search application on your php webapp that yields thousands of results. Of course these are divided in a nice paginated links. Without caching, everytime the user jumps from each paged result links, your app will query your database, which adds overhead.

By using caching, you're storing the result set in a temporary container(in case of memcached, it's the memory) so that only one call to the DB are done.

Here's the logic.

1. First check if we have cached the result set coming from DB.

2. If not, run the query.

3. Now, save the result set into cache.

4. If yes(see #2), get the result set from the cache.

Why Memcached? Well IMHO, it's fast and it's supported by php using libmemcache. You can see the complete details and can download it from danga.com

Can you provide sample snippet? See below.

<?php

// first we set up memcached connection

$memcache_obj = new Memcache;
$memcache_obj->connect($memcache_host, 11211);

// now let's check for cached data

if(!$memcache_obj->get('unique_key')) {

// your very large query here and assign the result in $resultset

// save the db result into the cache, set the cache lifetime for 5 minutes(60 sec * 5)

$memcache_obj->set('unique_key', $resultset, MEMCACHE_COMPRESSED, 300);

} else {

$resultset = $memcache_obj->get('unique_key');

}

// do useful things with the $resultset

?>

It's so simple , yet so helpful.

Previously

CodeIgniter 101

You want to use codeigniter but don't know where to start? Below are the lists to get you up and running. 1. Download the zip/tar package ... read on
© FROST