I added a simple voting mechanism to ajaxian.com a few months ago.
Since Ajaxian runs on Wordpress the pattern for this work was:
- Search for voting plugins
- Weed through the million plugins
- Find the best one for our needs
- Go through the plugin code and optimize it
This time was no different. We based our work on the Votio plugin, and tweaked things so the plugin wasn’t doing unnecessary calculations all the time.
The biggest sinner was the functions that take no variables.
As the pages are generated, they go through The Loop, where you get all of the blog entries given to you. We need to generate the ajax ratings form for each item, and to do that we just needed to add:
That function would access a global (gotta love PHP and “global $foo” :/) to get the current post object. Sounds fine right? We are in a loop of posts. We want to get the post.
It works at first, but what about if things change. For example, we want to do caching, and it is nice to dump out HTML that we can read in, instead of calculating these forms all of the time. In this case, the cache loader does NOT know about the loop of posts, as it is dealing with just HTML that it reads from cache.
I changed the API to be: votio_ballot_box($postId), and in The Loop I spit that out, so now when the cache is loaded it loads “votio_ballot_box(23)” and all is well.
A simple change. A stateless function. Now it is a lot more flexible.