brandontreb.com Tips And Resources For Software Consultants

The Only Twitter API PHP Class You Will Ever Need

twit

Note Twitter has switchted their entire interface to use OAUTH and this class no longer works (I should probably change the title hahaha). I will post an oauth connection tutorial in the near future, so make sure to ****subscribe to my RSS feed** for all of the sweet sweets updates!**

Cheers!

So, I started writing a Twitter API Programming series last week… Here is part 1. I have found that there is not much else to teach when it comes to interfacing with Twitter. Basically, we just need to implement all of the Twitter functions.

I have taken it upon myself to create a fully functional Twitter API PHP class. It has every Twitter function you will ever need (less the direct messages). I have also fully documented it with comments directly from the Twitter API so that the functions are easy to understand. Here is how you would use the class. The first parameter of every function is the return type. For Twitter it can be either xml, json, or rss for some functions.

<code class=’php’>include("Twitter.class.php");
    $twitter = new Twitter();
    $twitter->username = "twitteruser";
    $twitter->password = "twitterpass";
    // Show public timeline
    echo $twitter->public_timeline();
    // Update your status
    echo $twitter->update(‘xml’,’This PHP class is flippin sweet!’);
    // Start following a user
    echo $twitter->create(‘xml’,’brandontreb’);</code>

These are just 3 of the functions implemented in this class. The full function list includes:

  • public_timeline
  • friends_timeline
  • user_timeline
  • update
  • replies
  • friends
  • followers
  • show
  • create
  • destroy
  • exists

All of these functions are fully documented and simple to use. You can also check out Twitter’s API here (but you shouldn’t need to).

So, now you can fully **integrate Twitter into any PHP application you create! **

Download The PHP Twitter Class here Twitter.class.php

Also, make sure you subscribe to my RSS feed. More great programming tutorial to come.

Why Many iPhone Apps Suck

I have been downloading many different iPhone apps lately and have noticed that many of them suck.

When I say they suck, I’m not necesarily referring to the content of the app. What I am talking about is the programming of the app. But Brandon, how do you know the programming sucks. Well, frequent crashing is an obvious indicator. Also, taking too long to do various computations as well as overall awkwardness.

This is because many non-programmers or hobby programmers decide they want to make an iPhone app without first learning the objective-c language. People just use jank copy and pasted code frankensteined from different examples, close their eyes and pray. This is the architecture of many iPhone apps.

So, who’s fault is this? Well, at first I wanted to say Apple for their lack of tutorials/explanations. After thinking about it, I feel it’s simply lazy programmers driven by trying to make money rather than the desire create a solid and useful applications. It’s quite sad actually.

One challenge here is the iPhone is a terrible platform to learn programming with. The forced program design assumes you have a solid understaning of object oriented programming design patterns as well as many other advanced programming topics. Many CS students don’t even get this until their second year in college! So how can a novice programmer jump right in and make an iPhone app? They code a pile of crap.

So what’s the solution to this? Well I’ll tell you. Teaching people objective-c from the ground up (that, and Apple being more selective when approving apps). I intend to write a whole series of beginner objective-c tutorials (using the mac as a platform rather than the iPhone). I’m not sure yet if these will be posted here or on icodeblog.com. I have yet to decide.

So stay tuned for the first Mac Application Development tutorials.

Buzzword Is Now In The App Store

Well, after anxiously waiting for the past 6 days (feels like forever) I have finally gotten that magical email from Apple stating that my “application is ready for sale”. The application of course referring to a game I created called Buzzword.

Buzzword is essentially a clone of the popular party game CatchPhrase ported on to the iPhone. Click Here for all the details on Buzzword.

I am asking a huge favor to anyone that wants to participate. I will give you a free copy of Buzzword (wow saves you a whole buck) if you would kindly write a review of it on your blog or website. If you are interested, either post a comment in this post, contact me, or hit me up on Twitter.

Click on the image below to download Buzzword now.

Download Buzzword In The App Store

Twitter API Programming Tutorial With PHP – Intro

<img src="http://brandontreb.com/wp-content/uploads/2009/02/picture-15.png" alt="picture-15" title=&uuot;picture-15" width="400" height="125" class="alignnone size-full wp-image-85" />

I have recently started using Twitter and completely fell in love with it. Being a programming, this naturally made me want to develop applications for interfacing with it. So, I scoured the internet (checking Twitter’s website as well) to find good *simple tutorials for doing this. After searching for a while, I couldn’t really find any. Ok, I lied, I found a few but they were terrible. I hate tutorials that assume the reader knows more than they actually do.

So, I am taking it upon myself to write a series of comprehensive tutorials for interfacing with Twitter. I will first do them all in PHP and then maybe in some other languages. I may even do some in Objective-C to be implemented on the iPhone. These would be written of course at iCodeBlog.com 😉 .

Let’s just jump right in. Twitter offers a few ways to interface with their web services, which are all documented on their API Wiki. The documentation is great, assuming you know the code to get connected and make the calls. So, let’s skip all of the nerdy low level stuff and write an application.

Today, I will be teaching you how to simply connect to Twitter and update your status. This will be pretty straight forward and require very little PHP code. So, grab some coffee, open up your favorite PHP editor (notepad?).

Ok, so let’s start by wrapping our code into an easy to call function. We don’t want to have to copy and paste our Twitter interface code every time we need it in a project. Wouldn’t it be nice if we could just call it like this

<code class=’php’>updateTwitter("Just Rockin Out")</code>

So let’s begin by declaring a function called updateTwitter. Type the following code</p>

<code class=’php’>function updateTwitter($status){ 
    // Twitter login information 
    $username = "TwitterUsername"; 
    $password = "TwitterPassword";</code>

Our function begins with a declaration of a username and password. This will be your Twitter login information. Every Twitter API call requires that you authenticate yourself. Make sure you update the code to include your username and password/

Next, we will add the following code to initialize the variables needed to make our Twitter API call. Continue by adding the following code.

<code class=’php’>// The url of the update function 
    $url = ‘http://twitter.com/statuses/update.xml’; 
    // Arguments we are posting to Twitter 
    $postargs = ‘status=’.urlencode($status); 
    // Will store the response we get from Twitter 
    $responseInfo=array(); 
    // Initialize CURL 
    $ch = curl_init($url);</code>

One thing I want to point out is the URL. Notice the update.xml at the end of it. This is telling the Twitter API we want to call the update function and we expect to receive xml back. You could also change it to be update.json if you want to receive json data back.

The next variable postargs is simply the arguments we will pass to the update function. Since these arguments get appended to the URL, they need to be urlencoded. The responseInfo array will contain the return data from the cURL request to Twitter. Finally, we just initialize a new cURL session. cURL is just a protocol for transferring data. You can read up on it on Wikipedia if you feel so inclined.

Next, we need to tell cURL to do a POST rather than a GET and pass it our argument string

<code class=’php’>// Tell CURL we are doing a POST 
    curl_setopt ($ch, CURLOPT_POST, true); 
    // Give CURL the arguments in the POST 
    curl_setopt ($ch, CURLOPT_POSTFIELDS, $postargs);</code>

The next part is where the magic happens. Here is the next bit of code (I’ll explain it below)…

<code class=’php’>// Set the username and password in the CURL call 
    curl_setopt($ch, CURLOPT_USERPWD, $username.’:’.$password); 
    // Set some cur flags (not too important) 
    curl_setopt($ch, CURLOPT_VERBOSE, 1); 
    curl_setopt($ch, CURLOPT_NOBODY, 0); 
    curl_setopt($ch, CURLOPT_HEADER, 0); 
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    // execute the CURL call 
    $response = curl_exec($ch); 
    // Get information about the response 
    $responseInfo=curl_getinfo($ch); 
    // Close the CURL connection curl_close($ch);</code>

Wow! that looks like a lot of nerdy code. Good thing you only have to write it once and don’t have to understand it (unless you want to). The first line sets the username and password fields in our cURL call. When we first connect with the Twitter API, it will prompt for a username and password. cURL will automatically feed the username and password to the API. The next few lines are not super important. If you one of those people that get hung up on that sort of thing, you can read about them here. We’re almost done, I promise… Finally, we make the cURL call itself by calling curl_exec. This will return a response from Twitter which will contains some XML if your call completed successfully. The next line, gets the http response (makes sure you were able to connect to Twitter). If it is anything other than 200 (HTTP OK), it means your cURL request never even reached Twitter. Here is the last bit of code

<code class=’php’>// Make sure we received a response from Twitter 
    if(intval($responseInfo[‘http_code’])==200){ 
        // Display the response from Twitter 
        echo $response; 
    }else{ 
        // Something went wrong 
        echo "Error: " . $responseInfo[‘http_code’]; 
    } 
} 
?></code>

All this code really does is makes sure we got a 200 code (successfully reached Twitter). If so, it prints out the XML that Twitter returned to us. Now you have a handy-dandy function you can call whenever we want to update your Twitter status from your website. Simply type

<code class=’php’>updateTwitter("Just finished a sweet tutorial on http://brandontreb.com")</code>

and like magic, your Twitter status will be updated. This has many different uses as you can imagine. Join me next time when I will be putting this code into a PHP class as well as implementing the rest of the Twitter API functions. We will then be able to use this Twitter class in a variety of PHP applications. So , be sure to subscribe to my RSS feed and feel free to ask me any questions in the comments section of this post. You can also download the source code of this tutorial here… (insert clever tag line here (iCodeBlog’s is happy iCoding, I need a new one)).

Binary Game – iPhone App Review

Just posted an app review of B1nary Game over at FreshApps. Check it out!