Using Memcache with PHP

It's been at the back of my mind for a while, using objects from cache, without destructing them, and only initializing them once.

Many thanks to Memcache this is now possible. Memcached (daemon) stores arrays, objects and variables in memory available for clients to access them at any time. This speeds up the process of a web application a lot. Instead of having to create a new object each time the page is loaded, you can simply retrieve the desired object from Memcache and operate on it normally.

Memcache was fairly easy to get up and running to. Since I'm on Debian (lenny/sid), I was able to get it from the repository (apt-get install memcache). Or you can always compile it from source. Once that was setup, I then installed the memcache PHP extension, php5-mod-memcache, to allow PHP to interact with the Memcache daemon (memcached CLI).

There are some really nice features about Memcache, for instance, it allows you to use a pool of computers, perhaps a rack of hard drives, and to run a copy of Memcache on each of these. Therefore, using Memcache on the network across multiple machines.

Since this is just a testing server and development laptop, I was happy with the default memory allocation setting for Memcache, which is 64mb. Not that I'll use it all! (Maybe for extreme cases for stress testing / benchmarking). The maximum recommended size for each instance of Memcache is 2gb of allocated memory, which is really only useful for a production server, within a data center or the like.

Memcache also has a limit of 1mb for any given array, object or variable. Which is very useful, as this would most likely help prevent memory leaks and what not.

The Memcache daemon is fairly easy to get up and running too, with the -h parameter on a Unix box, you get the CLI argument options. I went pretty much default on this, with the extra -v and -vv for full verbose mode. This allowed me to see if everything was working correctly, which it was.

Overall, Memcache is an excellent new addition to my web development environment, and will hopefully use it for a long time!

jamesyb0i on August 13th 2008

Nice entry! Wonder if Memcache will be built into PHP 5.3, or perhaps 6. Wouldn't be sure on that though, since it interacts with the server. Would be good to see the extension in PHP by default though.