Skip to content
This repository has been archived by the owner on Dec 4, 2018. It is now read-only.
jmathai edited this page Sep 13, 2010 · 24 revisions

Table of Contents

  1. Efficiently using asynchronous curl
  2. Creating an application on Twitter
  3. Dependencies
  4. Class methods
  5. Accessing the response
  6. Uploading images using multipart
  7. Using the oauth_callback parameter

Getting started

EpiTwitter lets you asynchronously integrate with Twitter’s REST API using OAuth as the authentication mechanism. This means you can make non-blocking curl requests to Twitter’s API on behalf of another user without having them hand over their username and password.

Efficiently using asynchronous curl

EpiTwitter 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.

The key to using EpiTwitter 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.

  $twitterObj = new EpiTwitter(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET, $userToken, $userSecret);
  $followers = array('user1','user2','user3','user4','user5');
  $responses = array();
  // send off the requests in parallel
  foreach($followers as $follower) {
    $responses[] = $twitterObj->post_direct_messagesNew( array('user' => $follower, 'text' => "Hey {$follower} what's up?"));
  }

  // now we retrieve the results and ensure that each call completes
  foreach($responses as $response) {
    echo "Direct message had an id of {$response->id}\n";
  }

Creating an 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 EpiTwitter.

  define('TWITTER_CONSUMER_KEY', 'your_consumer_key');
  define('TWITTER_CONSUMER_SECRET', 'your_consumer_secret');

Dependencies

EpiTwitter has 2 dependencies including EpiOAuth and EpiCurl. EpiOAuth handles all of the authentication and url signing required to make valid requests to any OAuth provider, in this case Twitter. EpiCurl handles the asynchronous/non-blocking curl requests out to the API.

Class methods

EpiTwitter has only 2 methods, __construct and __call. The constructor takes a minimum of 2 parameters and a maximum of 4. The first two parameters are the consumer key and consumer secret. The last 2 are the OAuth token and OAuth secret which is what you’ll end up storing in your database for each Twitter account your users have granted you permission to acces.

The __call method handles the majority of the remaining 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.

Documentation on Twitter’s site.

  $twitterObj = new EpiTwitter(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET, $userToken, $userSecret);
  $userInfo = $twitterObj->get_accountVerify_credentials();
  // access keys directly
  echo "Your Twitter username is {$userInfo->screen_name}";
  // access response text
  echo $userInfo->responseText;
  // access response as an array
  var_dump($userInfo->result);

Understanding method names

EpiTwitter’s method names directly map to API endpoints. In the example above, the method name get_accountVerify_credentials consists of the HTTP method (get_) and the url path (account/verifycredentials). Simply follow these rules to determine the proper method name.

  1. The first part is the HTTP method (in lowercase) specified by the API docs (i.e. get, post) get
  2. Follow the method with an underscore get_
  3. 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
  4. The method takes an associative array as a list of parameters to be sent along with the request get_accountVerify_credentials(array('name'=>'value'))
  /* GET -> /followers/ids.json?screen_name=yahoo */
  $twtObj->get_followersIds(array('screen_name' => 'yahoo'));

  /* POST -> /statuses/update.json?status=This+is+my+new+status */
  $twtObj->post_statusesUpdate(array('status' => 'This is my new status'));

  /* GET -> /statuses/followers/jmathai_test.json */
  $userId = ucwords(strtolower($userId));
  $method = "get_statusesFollowers{$userId}"; // $userId = jmathai_test
  $twtObj->$method();

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 credentials API.

  {
    screen_name: "jmathai",
    name: "Jaisen Mathai",
    status: {
      text: "My last status",
      created_at: "Thu Apr 09 15:00:07 +0000 2009"
    },
  }

Each of these values can be accessed the following ways.

  // Access properties directly as member variables
  $userInfo->screen_name;
  $userInfo->name;
  $userInfo->status->text;
  $userInfo->status->created_at;

  // Access properties as an array through the response property
  $userInfo->response['screen_name'];
  $userInfo->response['name'];
  $userInfo->response['status']['text'];
  $userInfo->response['status']['created_at'];

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.

  [
    {
        screen_name: "jmathai",
        name: "Jaisen Mathai"
        ...
    },
    {
        screen_name: "jmathai",
        name: "Jaisen Mathai"
        ...
    },
    ...
  ]
  // Access properties via the response array
  $firstFollower = $resp[0]->screen_name

  // Loop over the response as an an array
  foreach($resp as $follower){
      echo $follower->screen_name;
  }

Uploading images using multipart

EpiTwitter supports uploading images via the Twitter API. 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.

  $twitterObj->post_accountUpdate_profile_image(array('@image' => '@/tmp/myfile.jpg'));

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.

  $url = $twitterObj->getAuthorizeUrl(array('oauth_callback' => 'http://mysite.com/custom/callback'));
  echo '<a href="'.$url.'">Authorize with Twitter</a>';

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.

  $token = $twitterObj->getAccessToken(array('oauth_verifier' => $_GET['oauth_verifier']));
  $twitterObj->setToken($token->oauth_token, $token->oauth_token_secret);
  $twitterInfo= $twitterObj->get_accountVerify_credentials();
  echo $twitterInfo->screen_name;
Clone this wiki locally