Now you need to make changes to the functional portions of the SignatureImage class. In order to implement caching we'll need to rewrite part of the fetchUserInfo method used for retrieving the user's Twitter feed information. Let's look at the method in its current form. private function fetchUserInfo($name) { $url = "http://twitter.com/statuses/user_timeline/{$name}.xml?count=1"; $xml = $this->curlRequest($url); if ($xml === false) { throw new SignatureImageException('User feed unavailable.'); } $statuses = new SimpleXMLElement($xml); if (!$statuses || !$statuses->status) { throw new SignatureImageException('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; } } To begin, we'll need to add another parameter to this function as well for passing in the location of the local cache folder. private function fetchUserInfo($name, $cache) { $url = "http://twitter.com/statuses/user_timeline/{$name}.xml?count=1"; Next, we need to add some logic. Currently, the function will begin by retrieving the user feed data from the Twitter API. Since we want this to be performed through our caching mechanism, we'll need to add a few If blocks to determine when and if a Twitter API call should be implemented. if ($xml === false) { throw new SignatureImageException('User feed unavailable.'); } We'll be replacing the above section of code with the code below. $cache = preg_match('#^(.*?)/$#i', $cache) ? $cache : "{$cache}/"; $cache_file = $cache . md5($url) . '.xml'; if (@filemtime($cache_file) + $this->cache_expires > time()) { $xml = @file_get_contents($cache_file); } else { $xml = $this->curlRequest($url); if ($xml !== false) { file_put_contents($cache_file, $xml); } } if ($xml === false && file_exists($cache_file)) { $xml = file_get_contents($cache_file); } elseif ($xml === false) { throw new SignatureImageException('User feed unavailable.'); } Here is the entire caching logic in its entirety. Let's take a look at this one piece at a time and see how it works. $cache = preg_match('#^(.*?)/$#i', $cache) ? $cache : "{$cache}/"; $cache_file = $cache . md5($name) . '.xml'; This first piece of code establishes some ground work. The first line will examine the contents of the $cache parameter (the local cache folder name). It uses a regular expression to check and add a trailing slash if necessary. The second line creates a file name that will be used to store or retrieve the cached user feed.
blog comments powered by Disqus |
|
|
|
|
|
|
|