I am currently requesting a twitter feed on each page load (I know this is wrong) like this:
json_decode(file_get_contents("http://api.twitter.com/1/statuses/user_timeline/{$username}.{$format}"));
Even with minimal traffic, twitter stops sending me the request before long. So after launching the website for my client – I am seeing perpetually unavailable twitter feeds.
The way I am imagining this working is checking the feed – storing it in a table with a timestamp, and choosing an interval – (say 10 minutes). On each pageload, check the timestamp, if the interval has not passed, pull the feed from the table, rather than twitter.
I know this would work, but given my last mistake being so silly, I wanted to make sure that there wasn’t another better practice.
Do I have it right this time?
That sounds exactly right. Three notes:
Put the date/time in one column and the twitter feed you want to show in another column, then you can just do a single select on that row and be done with it.
Store the rendered HTML in the database, not the JSON returned from Twitter. Then you’re only doing the transformation every ten minutes and not on every page request.
Do the time comparison all in the database or all on the server, don’t mix the two – I’ve run into problems with servers out of time sync that caused me big headaches. That is, don’t use a “INSERT … CURTIME() …” call and then compare that with a PHP generated date. My suggestion would be to generate a PHP date and store that, since time comparison in SQL can be tricky.