Zend_Service_Twitter

Single User Zend_Service_Twitter

When running a website for yourself or your company based on Zend Framework, you might want to show the Twitter messages to your audience.

Although the Zend Framework manual extensively describes how to set up a true Twitter application with the new OAuth implementation of Twitter using Zend_Service_Twitter and Zend_Oauth (since ZF-1.10.0), this is not what you’re looking for. You need a simple approach, using the single user OAuth implementation of Twitter.

Registration at Twitter.
Register your “app” to twitter at http://dev.twitter.com/apps/new where you’ll be presented a registration form for your app. Since it’s not really an app, you should register your website as the app.

Once registered, you need to accept the general terms for usage of the Twitter API.

Once accepted, your applications registered and you can start implementing it. But for a single user approach, you need to retrieve your access tokens.

Fetching tweets
Now it’s time to fetch those tweets and post them on your website.

Since these tokens are config elements, we store them in our application.ini as we keep this as our main configuration file for our whole website.

; Twitter service
service.twitter.oauth.username = “DragonBe”
service.twitter.oauth.oauth_token = “1234567-xPhPanDz3nDfRam3W0RkN0wW1THS1nGl3Z3nd0aUth”
service.twitter.oauth.oauth_token_secret = “8tH1sStr1nGmUstB3sT0r3ds0MwH3r3V3RryS3cr3t”

Now a simple model can be used to set up the verification process and retrieve the Twitter instance.

<?php
class Application_Model_TwitterClient
{
    protected $_config;   
    protected $_twitter;
   
    public function __construct()
    {
        $config = new Zend_Config_Ini(
            APPLICATION_PATH . ‘/configs/application.ini’, APPLICATION_ENV);
        $this->_config = $config->service->twitter->oauth;
        $this->_twitter = new Zend_Service_Twitter();
    }
   
    public function authenticate()
    {
        $accessToken = new Zend_Oauth_Token_Access();
        $accessToken->setToken($this->_config->oauth_token)
                    ->setTokenSecret($this->_config->oauth_token_secret);
                   
        $this->_twitter->setLocalHttpClient(
            $accessToken->getHttpClient($this->_config->options->toArray()));

        return $this->_twitter->account->verifyCredentials();
    }
   
    public function getTwitter()
    {
        return $this->_twitter;
    }   
}

Now we just need to call this model in our controller to retrieve the messages themselves

<?php
class IndexController extends Zend_Controller_Action
{
    public function indexAction()
    {
        $twitterClient = new Application_Model_TwitterClient();
        $result = $twitterClient->authenticate();
        $twitter = $twitterClient->getTwitter();
        $status = $twitter->status->userTimeline();
        $this->view->statusMsgs = $status;
    }
}

And in your view you just loop through those status messages

<li class=”myTweetList”>
<?php foreach ($this->statusMsgs as $tweet): ?>
<li><?php echo $this->escape($tweet->text); ?></li>
<?php endforeach; ?>
</ul>

Of course you need to add your own validation and caching to this code. But in a nutshell this works pretty damn good.

I’ve even build a model around retrieving those twitter messages and the actual properties of a Twitter status, but this is beyond the scope of this article.

If you find this information useful, or if you have a better approach, let me know in the comments.

Author:

by News Robot on October 2, 2010 in News, 1 Comment »
tags: , ,

TweetGT: an example of Zend_Service_Twitter via OAuth

TweetGT is a simple application that talks to Twitter. I wrote it as I couldn’t find another way to send a geotagged tweet sent from an arbitrary location.

Screenshot of tweetgt.funkymongoose.com

Also, my friend Cal Evans says that writing a Twitter app is the new Hello World, so I thought I’d better find out how to do it! Obviously, I used Zend Framework :)

The source is up on github so you can have a look at the entire project. The section I want to concentrate on in this post is the Twitter OAuth integration, which was added to Zend_Service_Twitter in version 1.10.6.

To implement my Twitter integration, I used a model, Application_Model_Twitter, which has a protected member variable to an instance of Zend_Service_Twitter. This means that the rest of the application has to go through the model to get to the service and so in principle at least, I get to control access.

OAuth integration requires that we get an access token from twitter. The basic process is that we hand off from our website to Twitter, who then call back to a URL on our site once the user has logged in.

Login: Redirect to Twitter

The loginAction looks like this:


    public function loginAction()
    {
        $twitter $this->_helper->twitter(); /* @var $twitter Application_Model_Twitter */

        // We need the request token for use in the callback when the user is
        // redirected back here from Twitter after authenticating
        $session = new Zend_Session_Namespace();
        $session->requestToken $twitter->getRequestToken();

        // redirect to the Twitter website
        $twitter->loginViaTwitterSite();
    }

Three things going on here. Firstly, I have set up an action helper to retrieve an instance of my model for me. This is mainly for ease of use as there’s a bit of configuration required, so having it centralised saves having to duplicate code. There’s other ways of doing this of course, but a action helper suited me this time :)

When we hand over to Twitter, we send a request token over too. We will need the request token in the call back so we store to the session ready for use after the user has authenticated on Twitter’s site.

Finally we do the redirect to Twitter’s site via a model method, loginViaTwitterSite, which simply proxies to the redirect method within Zend_Service_Twitter‘s OAuth consumer.

Instantiating the model

The model is instantiated within a controller action helper. To log in to twitter using OAuth we need a consumer key and a consumer secret that are available from Twitter on a per-application basis. I’ve chosen to store these in the application.ini file. We also need to configure Zend_Service_Twitter with the callback URL to use and, if we are logged in, the username and access token from Twitter. This action helper does all that for us and looks like this:


class Application_Controller_Helper_Twitter extends Zend_Controller_Action_Helper_Abstract
{
    /**
     * @var Application_Model_Twitter
     */
    protected $_twitter;

    public function direct()
    {
        if (!$this->_twitter) {
            $controller $this->getActionController();

            $config = array();

            $session = new Zend_Session_Namespace();
            if ($session->accessToken) {
                $token $session->accessToken;
                $config['username'] = $token->screen_name;
                $config['accessToken'] = $token;
            }
            
            $options $controller->getInvokeArg('bootstrap')->getOptions();
            $config['consumerKey'] = $options['twitter']['consumerKey'];
            $config['consumerSecret'] = $options['twitter']['consumerSecret'];

            $request $controller->getRequest();
            $url $request->getScheme() . '://' .  $request->getHttpHost() . $request->getBaseUrl();
            $config['callbackUrl'] = $url '/callback';

            $this->_twitter = new Application_Model_Twitter($config);
        }

        return $this->_twitter;
    }

}

I didn’t want my model interacting with sessions or the bootstrap options, so I used an action controller. I could equally have used a service layer object, or instantiated the model in the bootstrap or in a Front Controller plugin. The most important thing is that I only deal with the config of sorting out the config array that Zend_Service_Twitter needs once.

Callback

I have chosen /callback as the URL for Twitter to use. The easiest way to set this up is to have in indexAction() within a CallbackController class. This code will use the model’s twitter service to retrieve the access token and store it to the session.

It looks like this:

class CallbackController extends Zend_Controller_Action
{
    public function indexAction()
    {
        $session = new Zend_Session_Namespace();
        if (!empty($this->getRequest()->getQuery()) && isset($session->requestToken)) {

            // Get the model instance from the action helper
            $twitter $this->_helper->twitter(); /* @var $twitter Application_Model_Twitter */

            // turn the request token into an access token
            $accessToken $twitter->getAccessToken($this->getRequest()->getQuery(),
                    $session->requestToken);

            // store the access token
            $session->accessToken $accessToken;

            // we don't need the request token any more
            unset($session->requestToken);

            // redirect back to home page
            $this->_helper->redirector('index''index');
        } else {
            throw new Zend_Exception('Invalid callback request. Oops. Sorry.');
        }
    }

}

The code should be fairly self-explanatory with the inline comments to help :)

That’s it. We are now logged into Twitter and back on our own website able to do whatever we want to do :) Have a look at the source to see the rest of the details of how it all fits together.

Author: Rob…

by News Robot on September 14, 2010 in News, No Comments »
tags: , , ,

Raphael Stolt’s Blog: Utilizing Twitter lists with Zend_Service_Twitter

If your framework lacks some features, simply add it. This is exactly what Raphael Stolt did to add list feature support to Zend_Service_Twitter service.

Several months ago Twitter added the list feature to it’s public API. While debating some use cases for an event registration application I stumbled upon an interesting feature, which adds participants automatically to a Twitter list upon registration. This way registered and interested users can discover like-minded individuals and get in touch prior to any pre-social event activities. This post will show how this feature can be implemented by utilizing the Zend_Service_Twitter component, and how it then can be used in a Zend Framework based application.

In his post Raphael publishes his class extending Zend_Service_Twitter and adding missing functionality. He also shows how one can use it in controller to add users to Twitter’s list during registration.