Dependencies

PHP 5.2 or higher

EpiTwitter, EpiOAuth and EpiCurl (included with the repository)

Usage and examples

Some of the Twitter API endpoints require authentication while others don’t. For authenticated API calls you can provide credentials using either basic authentication or OAuth. Basic authentication requires that you send the username and password of the account you want to use. OAuth let’s you pass tokens, instead of passwords, to make authenticated calls. Twitter-async makes it easy by exposing an extremely simple API.

Accessing the response

All calls to Twitter APIs return an object with properties. The properties are named identical to what is in the response and dimensions of 2 or more are exposed as arrays. For example, the following JSON response is from the verify credentialsAPI.

A note on enumerated lists

Some responses are returned as an enumerated list. Since PHP requires that object properties start with [a-Z_] you can’t use $resp->0->screen_name. Given the following JSON response, you can use either of the methods described below.

// Access the respose as an array
$firstFollower = $resp[0]->screen_name
// Loop over the response as an an array
foreach($resp as $follower){
echo $follower->screen_name;
}

Catching and handling exceptions

Twitter-async throws an exception anytime the HTTP response code is not between 200 and 399. For debugging purposes, accessing responseText doesn’t follow this pattern and will always return the raw response. It’s recommended that you catch specific exceptions in favor of the base Exception. Here is an example of catching an EpiTwitterException and falling back to the base Exception.

NOTE: If you have set the library to operate asynchronously the exception isn’t thrown until you access any of the return values from the API call.

Method based API

The __call method handles the method based API invocations. There’s a simple naming pattern used to determine the proper method you want to call for a given API endpoint. Let’s start with the most common first example of validating a set of credentials.

Understanding method names

The method based API directly maps to API endpoints. In the example above, the method name get_accountVerify_credentials consists of the HTTP method (get) and the url path (account/verify_credentials). Simply follow these rules to determine the proper method name.

The first part is the HTTP method (in lowercase) specified by the API docs (i.e. get, post) get

Follow the method with an underscore get_

The second half of the method name is the URI path. This is entirely lowercase except for when there needs to be a / which is denoted by a capital letter get_accountVerify_credentials

The method takes an associative array as a list of parameters to be sent along with the request get_accountVerify_credentials(array('name'=>'value'))

Uploading images using multipart

Twitter-async supports uploading images via the Twitter APIusing OAuth. To specify the image parameter to the account/update_profile*image endpoints you’ll need to prepend the key and value with an @. The path to the file must be the absolute path to the file on the server. This is not yet supported with basic authentication.

$twitterObj->post('/account/update_profile_image.json', array('@image' => '@/tmp/myfile.jpg'));
// http://github.com/jmathai/twitter-async/issues#issue/68
// some people have issues with the image uploading and a suggested workaround is to add the mime type
$twitterObj->post('/account/update_profile_image.json', array('@image' => '@/tmp/myfile.jpg;type=image/jpeg'));

Using the oauth_callback parameter

In the 1.0a version of the API Twitter added support for an oauth_callback paramter. This parameter allows you to programmatically specify the callback url which Twitter redirects to. Originally, Twitter would always redirect the user back to the URL you specified in your OAuth settings.

To specify a different callback url you can pass in a parameter into getAuthenticateurl or getAuthorizeUrl.

Twitter associates the URL you specified with the OAuth token they give back to you. This url works like normal and when the user visits it they will be taken to Twitter’s OAuth page as normal. Once they authorize usage of your application then Twitter will forward the user to the URL you specified. They will include an additional parameter in the url named oauth_verifier. This parameter needs to be passed in to getAccessToken in order to exchange the request token for an access token. Aside from these two additional parameters the flow is identical except you can specify the callback URL at run time.

Efficiently using asynchronous curl

Twitter-async was carefully written to maximize the efficiency of making HTTP web service requests. Knowing that curl calls are expensive, we don’t want to wait around idly while we could be doing other work. This is especially true if you need to make multiple calls on a single page. Ideally, you could fire off several requests in parallel instead of doing them one at a time. To enable asynchronous calls you will need to call useAsynchronous(true) on the Twitter-async object.

The key to using Twitter-async efficiently is to delay accessing the results for as long as possible. Initiating the call fires off the HTTP request and immediately returns control back to you without blocking. The call continues to work in the background until you need the results. For the best performance it’s advised to initiate the calls as early as possible and only block by accessing the results as late as possible. The implementation details depend greatly on your framework.

Using the sequencer to verify asynchronous requests

It’s important to validate that your calls are truly asynchronous. The library includes a sequencer class which displays a graph of the calls to show you how the calls are sequenced. You can look at the file tests/sequencerTest.php for an example.

Creating an OAuth application on Twitter

To start off, you’ll need to create an application on Twitter. They will give you a consumer key and a consumer secret. Copy and paste this into your site’s configuration file since you’ll be needing them later. The rest of the information is embedded in Twitter-async.