December 22nd, 2010

  • PHP

Retweeting in CodeIgniter Using the Haughin Library

Sometimes the simplest things can be a real pain.  I'm building an app that needs to use OAuth to login to Twitter.  I'm also using CodeIgniter as my PHP framework.  Haughin made a nice library for CI, but for the life of me I couldn't get it to retweet.  It was driving me insane.  After trying to find another library I sucked it up and dove into the code to see if I could figure out what was wrong.  After a while I found it, the retweet api call has 3 segments, but the library only handles 1 or 2.

First you need to define whether this method needs to use post or get and if it needs OAuth, so in the call method I added this:

if(preg_match('/retweet/', $method)) {
    $http = "post";
    $auth = TRUE;   
}

Next I needed to modify the call method to handle more than 2 api segments.  I choose to make this specific for retweeting so I wouldn't break anything else.

if ( $this->oauth !== NULL )
{
    $parts = explode('/', $method);

    if(preg_match("/retweet/", $method)) {
        $method_string = $http.'_'.$parts[0].ucfirst($parts[1]).($parts[2]);
    }
    else if ( count($parts) > 1 )
    {
        $method_string = $http.'_'.$parts[0].ucfirst($parts[1]);
    }
    else
    {
        $method_string = $http.'_'.$parts[0];
    }
           
    $data = $this->oauth->$method_string($params);
    return $data->_result;
}