Re-using serialized PHP data

A friend of mine stumbled across the PHP function serialize() and thought it was pretty cool. It is pretty cool indeed. He was wondering how that can be used in a real example and how to extract/retrieve that serialize data later on.

My example will be based on performance requirements. Let’s say I have an application that requires a lot of computation which end up in a very small summary. For example, something that shows the number of users, the number of votes, the average vote value, the highest vote, all that based on some filters to narrow down the data set we are evaluating. Since this summary information is shown on every page of our site and since it takes 3 seconds to compute all this, loading any page on our site is painfully long. How about we cache the results? Caching the results into the database is possible but I will use a simple file to simplify my example. Choosing to use a file for caching instead database might be a good idea if your site does not depend on the database that much. Using a file should be even faster than a database call. If you have a farm of Web servers, using files would get complicated and database would be preferred. So using a database for caching is slower but more scalable in general.

In my example, I will use a hard coded summary array but in real life that will come from some function or class.

Let’s save the results into the cache.

$summary = Array('users' => 4591, 'votes' => 301, 'avg_vote' => 3, 'high_vote' => 5);
$bytes_written = file_put_contents('/path/to/cache', serialize($summary));

When it is time to get it back, we do:

$summary = unserialize(file_get_contents('/path/to/cache'));

I have skipped any error checking in this example but you have to consider checking for errors.

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <blockquote>
  • You may post PHP code. You should include <?php ?> tags.
  • Lines and paragraphs break automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>. Beside the tag style "<foo>" it is also possible to use "[foo]". PHP source code can also be enclosed in <?php ... ?> or <% ... %>.
  • Web page addresses and e-mail addresses turn into links automatically.

More information about formatting options