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.
When it is time to get it back, we do:
I have skipped any error checking in this example but you have to consider checking for errors.
Make a Payment to Christian Roy