Twitter is down, who cares

One of the component in the Zend Framework that I’m learning to love lately is Zend_Http_Client. If I remember correctly, back in the days, my first reaction on this component was:

Oh, this is for just for those who don’t know how to use curl_* functions. I don’t need that, pff

Then somebody, trying to convince me to use it, told me:

but you don’t understand! this is usefull if your php was build without cURL support

I hate the ‘if your php is built without…’ family of excuses. And what about if my webserver don’t have the required PHP > 5.2.4 as needed by Zend, or if it’ is built without PHP support, or if my server is without an OS? I must confess that I have always (eh, mostly) been working with company that have enough control on their server to make it easy for the developers. I strongly think that to create something great, one need some control on his environment. Would you like to have a surgery by a surgeon who don’t have access to all his tools?

Back on topic. First thing first, Zend_Http_Client makes your code easier to read, even after a while. cURL argument are like regular expression, you never totally forgot them, but you need to look at the documentation once in a while. To me, the main advantage is that you can tell your http client to use different adapter. And my favorite these days is the Test adapter. As the name implied, it is really usefull when doing (unit) test.

Using the Test adapter, I can simulate an answer from a website. This mean that I can work on some Twitter stuff and test them anytime, even if Twitter seems to always be down at the exact same moment I want/need to try something.

Here’s an example that simulate a search request, you first start by getting an example answer with curl on the command line (when Twitter is up) that you save into dummy.json:

curl -o dummy.json -i http://search.twitter.com/search.json?from=danceric

and then use this file to set the response with the test adapter

$client = new Zend_Http_Client();
$client->setUri('http://search.twitter.com/search.json');    
 
// Set the expected response
$client->setAdapter(new Zend_Http_Client_Adapter_Test());
$fakeResponse = file_get_contents('dummy.json');
$client->adapter->setResponse($fakeResponse);
 
$client->setParameterGet(array(
  'from' => 'danceric',
));    
$response = $client->request();
 
//let's pretend I want the result as an array
$searchResult = Zend_Json::decode($response->getBody());

Now I can have a result returned without contacting Twitter. it’s easy to create a set of dummy data for your different unit test. Of course this code is not to be used as is in a unit test…

Btw, Twitter is not always down. It just seems worse when you use it too much.

Posted Friday, May 15th, 2009 under php.

Comments are closed.