January 28th, 2004
Lessons
Constants are the bomb. I've been using the define() function in PHP to define session variables across the board; no more need to define "global" variables or use some ugly hack with (real) global variables.
Originally I thought the limitation of the constants were that they couldn't store anything other than strings and variables; they couldn't store hashes.
But I found out that if you use the serialize() function in PHP, you can convert a hash to a string (of sorts). So then simply store this as a constant, then unserialize() it when you need to grab the data.
A real application of this has been for the generation of lists. For example, let's use the TokkiProject website (the hyori gallery is a good example).
Right now, on each page's generation, the script hits the database many times to grab the imageids for a given albumid. Let me give you a graphical view of the database in question:
---------------------------------------
| IMAGEID | ALBUMID |
----------------------------------------
| 2 | 1 |
| 4 | 1 |
| 234 | 1 |
----------------------------------------
So for each page generation in Tokki currently, the database gets hit three times so I can generate the "next image," "previous image", and the page navigation on the bottom.
This is bad practice. The albums aren't updated that often; ideally the "total" imageid listing should be stored somewhere more static. With a large gallery like hyori, I would imagine the database gets hit about 1500 times PER page generation.
So if we were to create a hash of the imageids (call it TOTIMAGEID) and store it someplace (memory? flat file? db? it's irrelevant) with a timestamp ... upon every page view, we could bring up the timestamps of the last updated time for the album and the timestamp for the TOTIMAGEID) and do a quick comparison. If the album has been updated, *then* hit the database and update the imageids. Otherwise, just use the exiting TOTIMAGEID.
With serialize(), it's really easy to just take that hash and store is a string somewhere. Wooooooooooo.