Open SourceIntegrating Twitter Into the Zend Framework

Integrating Twitter Into the Zend Framework

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

I’ll admit I’m a rather late adopter of Twitter, the real-time short messaging service that has in recent months taken the tech community by storm, and has as of late seen adoption by organizations such as The Wall Street Journal, Dell, Whole Foods, and the Cleveland Plain Dealer (see twibs for a comprehensive business listing).

My interest in the service changed during the course of CodeMash, an annual developer’s conference I co-founded. As it turns out, most of the CodeMash attendees are avid Twitter users, and were regularly posting thoughts regarding their experience attending the various sessions and other functions. Naturally, the organizers were very interested in these posts, using them as one of the barometers for gauging success. The easiest way to keep tabs on the posts was by way of Twitter’s great search interface.

As it turns out, though, there are quite a few other ways to track Twitter trends, and even build your own interfaces for posting messages to your Twitter account, not to mention monitoring the posts of your friends. If you’re looking for eye-candy, one of the most interesting applications is Twittervision, a mashup pinpointing the location of posting users. Tracking your post frequency is easy using TweetStats. Or, check out emotionally-inspired posts at twistori. View hundreds of other available Twitter-oriented applications at the Twitter Fan Wiki. All of these compelling solutions are possible using the fantastic set of Twitter APIs made available thanks to the Twitter team.

Using these APIs, a number of Twitter clients also have popped up. twhirl (see Figure 1) is probably the most notable example for desktop users, although iPhone and iPod clients are available, as are Google and Opera gadgets.

Figure 1: The twhirl Twitter Client

But, what if you wanted to create your own client, or integrate your Twitter stream into your blog or website? Indeed, if your main goal in starting a Twitter account is to post messages regarding a specific product, service, or organization, it might be most convenient to integrate an update mechanism into your existing content management system. Further, you might use Twitter’s infrastructure as a solution for keeping your website visitors up to date regarding new features and other announcements by integrating the stream into your website’s news page. Using the aforementioned APIs, the sky is really the limit in terms of what you can do! In this tutorial, I’ll show you how I integrated the newly launched GameNomad Twitter companion into http://www.gamenomad.com/, creating a useful news feature without having to deal with creating an interface and database table solely for managing news-related posts.

Introducing Zend_Service_Twitter

The Zend_Framework’s Zend_Service_Twitter component presents an easy solution for communicating with the Twitter infrastructure, offering the ability to log in to Twitter, retrieve and post messages, reply to friends, and interact with practically every other aspect of the Twitter service. In just minutes, I used this fantastic component to publish the latest posts from the GameNomad Twitter companion to http://gamenomad.com/news.

Figure 2: Integrating Twitter Into GameNomad

Integrating this feature into the GameNomad website took surprisingly little time. To begin, you’ll need to update the config.ini file to include your Twitter account’s username and password. If you don’t already have a Twitter account, take a moment to do so; it’s quick and easy.

Update the config.ini file

Always intent on centralizing all configuration parameters within the Zend Framework’s config.ini file, the first task you should undertake is updating this file to include your Twitter account’s username and password:

twitter.username = "gamenomad"
twitter.pswd     = "supersecret"

Be sure to save the file, and move on to the next step.

Create the News Controller

Next up is the creation of the controller used to retrieve the Twitter posts (or “tweets”, as they’re typically called). I’ve chosen the name “News”, although you’re of course free to use any name you please. Implementing the basic feature of logging in to the Twitter service and retrieving the latest tweets is done with remarkably little code:

Listing 1: The News Controller

class NewsController extends Zend_Controller_Action
{
   public function indexAction()
   {
      // Retrieve the configuration handle
      $this->config = Zend_Registry::get('config');

      // Connect to the Twitter service
      $twitter =
         new Zend_Service_Twitter($this->config->twitter->username,
                                  $this->config->twitter->pswd);

      // Retrieve a list of the user's latest 20 posts
      $this->view->posts = $twitter->status->userTimeline();
   }
}

The default number of posts retrieved is 20, although you’re free to change that value by passing the count parameter into the userTimeline() method:

$this->view->posts =
   $twitter->status->userTimeline(array("count" => 5));

Create the News View

Next up, you’ll need to create the corresponding view. Although numerous pieces of post-related information are exposed via the Twitter service, for your purposes I’ve only referenced three (created_at, user->screen_name, and text). If you’d like to review what else is available, pass $this->posts into the var_dump() function.

Listing 2: The News View

<h1>The Latest Gaming News</h1>

<?php if (count($this->posts) > 0) { ?>
   <?php foreach($this->posts AS $post) { ?>

      <p>
      On <b><?php echo date('m.d.y @ H:m:s',
         strtotime($post->created_at)); ?></b>,
      <b><a href="http://www.twitter.com/<?=
         $post->user->screen_name; ?>">

         <?= $post->user->screen_name; ?></a></b> said:<br />
      <?php echo ereg_replace("[[:alpha:]]+://
        [^<>[:space:]]+[[:alnum:]/]",
         "<a href=""></a>", $post->text); ?>

      </p>
   <?php } ?>
<?php } ?>

Automating Posts

Although not yet integrated into GameNomad, I’ve been thinking about automating posts that identify the currently hottest game as identified by Amazon.com’s sales ranking system (GameNomad tracks the sales ranks for more than 500 games). Via a cron job, the sales ranks are updated every six hours and inserted into the GameNomad database. Via the Zend_Service_Twitter component, updating the GameNomad Twitter account with this information is really easy; just connect to the service and call the status->update() method:

$this->config = Zend_Registry::get('config');
$twitter =
   new Zend_Service_Twitter($this->config->twitter->username,
                            $this->config->twitter->pswd);
$response = $twitter->status->update(Hottest game of the moment:
   Call of Duty: World at War);

This feature will soon be integrated into the site, so stay tuned!

Where to From Here?

Integrating Twitter into your website using the Zend Framework’s Zend_Service_Twitter component is a great example of this popular framework’s power. Check out these links for more information regarding how to continue the integration process!

About the Author

Jason Gilmore is founder of a publishing, Web development, and consulting firm based out of Columbus, Ohio. Formerly Apress’ open source editor, Jason fostered the development of more than 60 books, along the way helping to transform their open source line into one of the industry’s most respected publishing programs. He’s the author of several books, including the best-selling Beginning PHP and MySQL: From Novice to Professional (currently in its third edition), Beginning PHP and PostgreSQL: From Novice to Professional, and Beginning PHP and Oracle: From Novice to Professional.

Jason is co-founder of CodeMash, a nonprofit organization tasked with hosting an annual namesake developer’s conference, and was a member of the 2008 MySQL Conference speaker selection board.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories