Beyond building the most capable and appealing website possible, one of your highest priorities should be ensuring blazing fast load times. Not only will a highly responsive website increase visitor retention, but it will also positively affect your search engine results.
You probably know one of the easiest ways to improve performance is by caching all or parts of a page. But what might not be so obvious is exactly how this is accomplished. As it happens, a great solution called Memcached makes it trivial to incorporate caching into your website with great effect. In fact, relied upon by some of the largest websites in the world, among them Facebook, Twitter, Zynga, and YouTube, Memcached has essentially become the de facto website caching solution!
An open source project, Memcached’s great advantages are available to any developer with a need for speed. With dozens of APIs available for all of the most popular Web development languages, PHP included, chances are the integration process is easier than you think.
Installing the PHP Memcached Extension
To begin, you’ll need to install Memcached, subsequently starting the Memcached daemon. By default the daemon will run on port 11211. Be sure to write that number down as we’ll return to it later. If you’re running a Linux/Unix variant, then Memcached is almost certainly available via your respective package manager. On Ubuntu I installed it like so:
$ sudo apt-get install memcached ... Processing triggers for man-db ... Setting up memcached (1.4.5-1ubuntu2) ... Starting memcached: memcached.
If you’re running an alternative operating system, notably Windows, consult the Memcached website for documentation and other notes.
Next up, you’ll want to obtain one of PHP’s Memcached APIs. You’ll often find two PHP-specific Memcached extensions referenced within documentation and other tutorials, notably PECL/memcache and PECL/memcached. I suggest using the latter for a variety of reasons, which have already been covered in some detail elsewhere.
After installing the libMemcached library, you can install the aforementioned memcached extension via PECL:
$ pear install pecl/memcached
Alternatively everything may be conveniently bundled within your operating system’s package manager. For instance on Ubuntu installing the memcached extension and library is as simple as this:
$ sudo apt-get install php5-memcached
With Memcached and PHP’s memcached extension installed, you’re ready to begin caching!