Archive

Posts Tagged ‘memcache’

Introducing LayerCache

August 26th, 2009

I’ve recently started a new project, called LayerCache. It’s an easy-to-use caching framework for PHP5, which allows you to cache items in multiple layers. When a requested item isn’t present in one layer, the framework reads from the next layer in the stack. If the item isn’t present in any layer, it’s retrieved from the source and stored in all caches in the stack.

An example of usage would be caching user profiles in Memcache (bigger, slower, global to all webservers) and APC (smaller, faster, local to each webserver). It also offers a mechanism called prefetch, which aims to reduce the database hit when an item is removed from the cache because of age (ttl).

Currently, the framework offers interfaces to Memcache, APC, file caching and local caching (PHP array with LRU, caching in a request scope). I’ll probably add more caching interfaces support as the project evolves. There is no documentation, apart from examples (see link bellow) and unit tests (yes, that counts as documentation). The current code is fully tested with PHPUnit, but no stable package is currently available.

For more, visit the following links:

array() == false

March 7th, 2009

Yesterday I’ve noticed that too many queries are sent to the database server, even though the result should be cached in memcache. After digging into the source and testing, I’ve discovered something like this:

  1. $results = $memcache->get('key');
  2. if (!$results)
  3. {
  4.   $results = $this->fetchFromDb();
  5.   $memcache->set('key', $results);
  6. }
  7. return $results;

The fetchFromDb() method returned an empty array, which was stored in memcache. But, as it turns out, the bug was in checking of $results. An empty array evaluates to false when checking for true/false. I knew that already, but I missed this one.

So, the script issued a query, even though it already had a result. Luckily, this only happened with empty result sets, so the query was fast, and didn’t overload the server.

The correct code would be:

  1. if ($results === false)

I’ve lost quite some time over this, so I’m posting this as a reminder: if possible, use strict checking.

Author: Gašper Categories: Thoughts Tags: ,