I'm aware that serializing is used to convert data types into a storable format, for purposes such as caching.
What I'm more specifically asking is, what are the circumstances in which you should actually decide to store data ( using serialize()
in PHP, pickle
module in Python, et cetera )?
Let's say we had a high traffic website, and in our /blog
page we are using static content xml files, a gettext mo file, and dynamically generated content from a database.
Example #1:
The file we rely on for static content is en/blog.xml
:
'<content><![CDATA[
<h1>Welcome to my blog!</h1>
<p>Lorem ipsum dolor sit amet..</p>
]]></content>'
Would we want to serialize this xml file itself and store it in cache?
Example #2:
We also have a dynamically generated form, normally I would assume I would not serialize anything because it's server-side generated and dynamic, but our form field labels are internationalized and the user requested this page in spanish, therefore we are using a translation class which grabs form field labels stored in mo/csv/xml
format.
Contents of contact-us.php
:
<label for="first_name"><?php echo $L->_("First Name");?></label>
<input id="first_name" name="first_name" type="text">
The "First Name" message id translation is pulled from the application-level translation file, which we parse and store in an array which resides in our translation class. So it would be ideal for our code to not parse the mo
file on every page request, and instead serialize the whole array after parsing the mo, and then rely on the serialized dump of that?
Example #3:
Let's say on our blog page we're pulling in the 5 most recent blog posts.
$posts = BlogClass->sql('SELECT blog_message, blog_author FROM blog_posts LIMIT 5 ORDER BY blog_date DESC');
Would we want to rely on something like memcache and just set a key to the result of the sql statement, would it serialize the results of the query, or?
Bonus:
If anyone could actually provide specific examples of efficient/practical uses/mis-uses of serialization, that'd be great - something like a multi-page, huge huge form that pulls in database information and stores stuff in sessions, or any examples where you had to rely on serialize..