Stylized line drawing of mark playing the flute

Basics of the Alternative PHP Cache (APC)

We're going to talk, briefly, today about the Alternative PHP Cache (APC) which can be used to cache data at the application level. Keep in mind that this is very different than storing data in the SESSION object (which disappears when the session is over) and is only accessible by that particular SESSION. Data stored in the APC lasts indefinitely if you haven't specified a TTL (time-to-live) and is accessible across all SESSIONS.

Using it is pretty simple. Plop data into the cache by calling apc_store(), get the data back out by calling apc_fetch(), and remove it from the cache by calling apc_delete().

You'll also notice the function apc_add() which does the same thing as apc_store() except that apc_add() will not overwrite an existing value in the cache.

In general, you can put just about any kind of object into the cache. The only exception is an array of objects, in which case you need to wrap the array with the ArayObject wrapper.

So what's it good for?

Technically, you can use it to pre-compile a PHP file into a bytcode to speed up execution (although I haven't used that functionality personally).

I mainly use it for caching the results from large database queries so I don't have to keep hitting the database over and over.

For example, here's the profiling information for a random test database query:

image

And here's the profiling info for pulling that same information from the cache:

image

As you see, a decent amount of speed-up for not very much extra work.