Before we get too involved, let’s take a moment to look at the code that we’ve built so far. class SignatureImage { private $screen_name; private $profile_image; private $status_text; private $local_avatar;
public function __construct($name, $bg_image, $adir) { $this->fetchUserInfo(strtolower($name)); $this->fetchAvatar($this->profile_image, $adir); }
private function fetchUserInfo($name) { $url = "http://twitter.com/statuses/user_timeline/{$name}.xml?count=1"; $xml = $this->curlRequest($url); if ($xml === false) { // User feed unavailable. } $statuses = new SimpleXMLElement($xml); if (!$statuses || !$statuses->status) { // Invalid user channel. } foreach ($statuses->status as $status) { $this->status_text = (string) $status->text; $this->profile_image = (string) $status->user->profile_image_url; $this->screen_name = (string) $status->user->screen_name; break; } }
private function curlRequest($url) { if (!extension_loaded('curl')) { // PHP extension CURL is not loaded. } $curl = curl_init($url); curl_setopt($curl, CURLOPT_HEADER, false); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); $result = curl_exec($curl); if (curl_errno($curl) !== 0 || curl_getinfo($curl, CURLINFO_HTTP_CODE) !== 200) { $result === false; } curl_close($curl); return $result; }
private function fetchAvatar($url, $adir) { $fname = end(explode('/', $url)); $adir = preg_match('#^(.*?)/$#i', $url) ? $adir : "{$adir}/"; $fname = $adir . $fname; if ( !file_exists($fname) ) { $img = $this->curlRequest($url); $fp = fopen($fname, 'w'); fwrite($fp, $img); fclose($fp); } $this->local_avatar = $fname; } } The code we have so far will accept a user name and retrieve the XML status feed using the Twitter API. Then it parses that information, assigns some class-level variables, and creates a local copy of the user’s Twitter avatar. Now we need to assemble these pieces into a single “signature” image. To do that we’ll create a function called renderImage. So let’s go ahead and complete the class’s constructor with a call to this function. public function __construct($name, $bg_image, $adir) { $this->fetchUserInfo(strtolower($name)); $this->fetchAvatar($this->profile_image, $adir); $this->renderImage(); }
blog comments powered by Disqus |
|
|
|
|
|
|
|