a simple Twitter class
Download ViewRecently, I finally gave in to web-pressure and signed up to Twitter (@ironhamster88), more because of it's nice API than anything else.
Obviously, for any developer, the next step was using the API to fetch some data and do something with it, and at that time, the only useful thing I could think of was to use the API and fetch some statuses, and then stick them on my website.
The problem was, XML requests takes time, users don't like time. I wouldn't want to visit someone's web page and have to wait 20 seconds or so whilst some code fetches some data that isn't really of any direct relevance to the content of the site.
The solution was the have the code executed in a file, that is executed with a cron job, in the background, say every hour. The results of the request are then stored in a database and to load the data, the page displaying it simply makes a request to the database for that information. Much faster. Ok so thats the problems out of the way, let's get down to the classes.
A file containing both classes and the implementor can be found as a Pastie page by clicking the View link above.
I am using two classes for this, twitter.class.php and cron.class.php, both detailed below.
twitter.class.php
This class fetches the data (and/or sends) to/from Twitter.
<?php
/**
* @author Pete Robinson
*/
class Twitter
{
// The common section of the twiiter url
protected $baseUrl = 'http://twitter.com/statuses/';
// Your twitter username
protected $username = 'username';
// Your twitter password
protected $password = 'password';
// an array to store the fetched data
public $statuses = array();
// method to get the (3) most recent statuses.
public function apiStatuses($count = 3)
{
// get contents of the XML file holding my statuses
$xml = new SimpleXMLElement(file_get_contents($this->baseUrl . 'user_timeline/' . $this->username . '.xml?count=' . $count));
// loop through the xml object assigning each obj->text element to a variable in the $statuses array
foreach($xml->status as $stat) {
$this->statuses[] = $stat->text;
}
}
// method to fetch the statuses from the database, ordering by rank.
public function getStatuses()
{
return DB::select('*', 'tweets', '', 'rank ASC');
}
// method to update status. I'm not using this at the moment, although I do know it works.
public function updateStatus($status)
{
// initialise the cURL request to baseUrl/update.xml
$ch = curl_init($this->baseUrl . 'update.xml');
// assign class properties to variables
$user = $this->username;
$pass = $this->password;
// set username and password string
curl_setopt($ch, CURLOPT_USERPWD, "$user:$pass");
// set the status
curl_setopt($ch, CURLOPT_POSTFIELDS, 'status=' . $status);
// execute the curl request
$output = curl_exec($ch);
// close cURL connection
curl_close($ch);
// return the output of the request. When/if I start using this properly, i will implement error checking and the like.
return $output;
}
}
?>
cron.class.php
cron.class.php is a class that extends twitter.class.php and is executed by the implementor file. This will run the twitter class, take the results and insert the results into the DB.
The DB static class is my own class that I use to handle queries. You can quite easily modify the code to use a standard query, or implementation with your own DB class here.
<?php
/**
* @author Pete Robinson
*/
class Cron extends Twitter
{
// construct the object
function __construct()
{
// use apiStatuses method defined in twitter class to assign 3 most recent statuses to an array
$this->apiStatuses();
// ensure that statuses have been retrived.
if($this->statuses) {
// set the fields for DB insert.
$fields = array('status', 'rank');
// delete all existing tweets in DB
DB::delete('tweets', "tweet_id > '0'");
$i = 1;
// loop through the $statuses array, assigning each one to $values['status'] and setting the rank;
foreach($this->statuses as $stat) {
$values['status'] = $stat;
$values['rank'] = $i;
// insert the tweet into the DB
DB::insert('tweets', $fields, $values);
// increment the rank.
$i++;
}
}
}
}
?>
Implementation
This the implementor file. This file instanciates the cron class (and consiquentially the twitter class) and allows them to do their 'thang'. This file is called via cron using a curl request (I was using lynx but curl is faster). The request would be something like: curl http://mysite.com/twitter.php?t=1.
The $_GET variable t is in there so that if the page is accessed by someone accidentally, or via any other form (bot etc), the code is not run unless the $_GET variable 't' has a value of 1.
<?php
require_once('/path-to-class-lib/twitter.class.php');
require_once('/path-to-class-lib/cron.class.php');
if($_GET['t'] == '1') {
new Cron();
}
?>
And then on the front end of my site, all I do is perform a query to fetch the contents of the twitter table, ordering my rank and loop through the results, displayind each one. Enjoy.

