Difference between #3 and #7 of
How To Connect With Twitter From Yii

Changes

Title unchanged

How To Connect With Twitter From Yii

Category unchanged

Tutorials

Yii version unchanged

Tags changed

twitter

Content changed

[...]
First off, you must have the psYiiExtensions installed on your web server and Yii has to know about it. Please see the installation instructions for more information.

Secondly, you must have the PHP oauth extension loaded. Details for installing this are on the [psYiiExtensions wiki](http://code.google.com/p/ps-yii-extensions/wiki/PHPOAuthSupport).

OAuth
=====-----
The Twitter API uses OAuth as a method of remote authentication. I do not claim to be an OAuth expert, I just coded a wrapper for the excellent PHP oauth extension. However, in doing so I did learn a little which I will impart upon you now.
[...]
Step 1: Create your Twitter application
=================================--------------------------------------- Before integrating with Twitter, you'll need to create an application on the Twitter web site. This is done by [going here](http://twitter.com/oauth_clients/new) (http://twitter.com/oauth_clients/new) and filling out the information. Most of the information asked of you is rudimentary. However, one item deserves attention. This is the <b>Callback URL</b>. ### Callback URL ------------
 
The Callback URL is the URL on <b>YOUR</b> web site to which Twitter will redirect <b>after</b> a user has authenticated against the Twitter system. In my implementation I used a callback url of http://www.mysite.com/site/twitter. ### Save and Create ---------------
 
Now, press the 'Save' button to create your application. ### Consumer Key & Secret ---------------------
 
The top two, the Consumer Key and Consumer Secret are the important ones here. These are your API keys. They allow your application to "talk" to Twitter's API. Copy these down for now, we'll need them in the next step. You can always revisit the link above to see them again, so no worries if you've already clicked-through. Step 2: Configure Yii =====================--------------------- Now that you've told Twitter about your application, we need to tell Yii to create the Twitter component. This is done in the main.php configuration file. If you have not yet configured your main.php for the psYiiExtension library, do so now by following the installation instructions. Add the following code to your 'components' array: <pre>
 
 
```php 
// Twitter API 'twitter' => array(     'class' => 'pogostick.components.twitter.CPSTwitterApi',     'apiKey' => '<b>your_consumer_key</b>',
 
',
 
    
'apiSecretKey' => '<b>your_consumer_secret</b>',
 
',
 
    
'apiBaseUrl' => 'http://twitter.com',     'callbackUrl' => '<b>your_callback_url</b>',
 
',
 
    
'format' => 'array', ), </pre>``` Be sure to replace the bold text items with the information you entered and obtained when you created your Twitter application in step #1. Step 3: Integration ===================-------------------
There are basically two methods of integrating with Twitter:
[...]
In either case, you'll need to obtain an access token from the Twitter OAuth server. This is done by calling the <b>authorize</b> URL.
In the code sample below is ALL the code from my views/site/twitter.php (also my callback URL)
.: ### vews/site/twitter.php ###
 
 
<code>
 
&lt;
 
```php 
<
?php $this-&gt;>pageTitle=Yii::app()-&gt;>name . ' - Attach to Twitter'; ?&gt;
 

 
&lt;
?>
 
 
<
? if ( ! Yii::app()-&gt;>twitter-&gt;>isAuthorized ) { ?&gt;
 
&lt;h1&gt;
>
 
<h1>
Link your Twitter Account!&lt;/h1&gt;
 

 
&lt;
</h1>
 
 
<
div class=&quot;"yiiForm&quot;&gt;
 
&lt;
">
 
    <
?php echo CHtml::form(); ?&gt;
 
&lt;div class=&quot;simple&quot;&gt;
 
>
 
        <div class="simple">
 
            
Click the button below to be taken to &lt;<a href=&quot;"http://www.twitter.com/&quot;" target=_blank&gt;>Twitter&lt;/a&gt;</a> to link your account. &lt;br /&gt;
 
&lt;br /&gt;
 
&lt;br /&gt;
 
&lt;a href=&quot;&lt;
            <br />
 
            <br />
 
            <br />
 
            <a href="<
?=Yii::app()-&gt;>twitter-&gt;>getAuthorizeUrl()?&gt;&quot;&gt;&lt;>"><img src=&quot;"/images/twitter_sign.png&quot;" border=&quot;0&quot; alt=&quot;Sign in with Twitter&quot; /&gt;&lt;/a&gt;
 
&lt;/div&gt;
 
&lt;/form&gt;
 
&lt;/div&gt;&lt;
"0" alt="Sign in with Twitter" /></a>
 
        </div>
 
    </form>
 
</div><
!-- yiiForm --&gt;
 
&lt;
>
 
<
? } else { ?&gt;
 
&lt;h1&gt;
>
 
<h1>
Linked with Twitter!&lt;/h1&gt;
 

 
&lt;
</h1>
 
 
<
div class=&quot;"yiiForm&quot;&gt;
 
&lt;
">
 
    <
?php echo CHtml::form(); ?&gt;
 
&lt;div class=&quot;simple&quot;&gt;
 
>
 
        <div class="simple">
 
            
Your account is currently linked to your Twitter account &lt;b&gt;&lt;<b><?= Yii::app()-&gt;>twitter-&gt;>screenName ?&gt;.
 
&lt;br /&gt;
 
&lt;br /&gt;
 
&lt;br /&gt;
 
&lt;/div&gt;
 
&lt;/form&gt;
 
&lt;/div&gt;&lt;!-- yiiForm --&gt;
 
&lt;? } ?&gt;
 
</pre>
 
 
Capturing the Access Token
 
--------------------------
>.
 
            <br />
 
            <br />
 
            <br />
 
        </div>
 
    </form>
 
</div><!-- yiiForm -->
 
<? } ?>
 
```
 
 
### Capturing the Access Token
After the user has authenticated with Twitter, your callback is called and the psYiiExtension library will pull out the new token and retrieve the permanent access token. It is up to you to store this someplace. The library places the token in a user session state. You can retrieve the token via: <pre>
 
 
```php 
if ( Yii::app()->twitter->isAuthorized )     $_arToken = Yii::app()->twitter-><b>getToken()</b>; else     echo 'User is not authorized'; </pre>```

The token is actually an array with two (or more once authenticated) elements. After authorization, the array contains the following elements:
[...]
Save these off for later use. You can use a session variable or store them in your database.

### Authorization Event
 ### An alternate to this method is to use the <b>onUserAuthorized</b> event. This event is generated by the CPSOAuthComponent when authorization is complete. You must subclass CPSTwitterApi to capture this event and do with it what you please. Not a big deal, and kinda cool, no? ### Return trips to the site and reloading the token ##
 

After the session ends, the tokens are lost and you will need to load up your stored access tokens for the current user (or your site). This is done via the <b>CPSTwitterApi::loadData()</b> method.
It is up to you where you do this. Preferably, find a place where you actually need to use the Twitter API and load it there. Otherwise you'll end up loading it every time a page is loaded from your site and that's not very fast or Yii-like.
[...]
Here's the code:

<pre>
 
```php

<?php
/**
[...]
* @license http://www.pogostick.com/license/
*/

 
/**
* CPS provides
*
[...]
class CPSWebUser extends CWebUser
{
//**************************************************************
****************** //* Member variables //********************************************************************************

/**
[...]
protected $m_bLoaded = false;

//**************************************************************
****************** //* Private methods //********************************************************************************

/**
[...]
}

//**************************************************************
****************** //* Yii Overrides //********************************************************************************

/**
[...]
}
}
    }
 
</pre>
}
 
```


Now my site allows multiple identities (i.e. Facebook, Twitter, Flickr, etc.) and I needed a single management point. I have a table that stores the token information for each platform.
[...]
This looks up my tokens from the database and pre-loads them into the various platform objects like Twitter:

<pre>
 
 
```php 
Yii::app()->twitter->loadData( 'user_id', 'screen_name', is_authenticated, array( 'oauth_token' => oauth_token, 'oauth_token_secret' => oauth_token_secret ) ); </pre>``` Once you make that call, you're all set to use the Twitter API! Step 4: Make Twitter API Calls! #
 
-------------------------------

Now you've got it all set up, all you need to do is make a call to the Twitter API. The CPSTwitterApi object handles all the nasty OAuth token passing and whatnot to let you concentrate and retrieving and using Twitter data.
Almost all of the Twitter API functions have been converted to single methods in the CPSTwitterApi class. Have a look-see through there and you'll see all the calls you can make.
[...]
So, here's a sample call I made to get mentions of my Twitter account:

<pre>
 
 
```php 
$_arResults = Yii::app()->twitter->getMentions(); echo var_export( $_arResults, true ); </pre>``` Produces: <pre>
 
```php

array (
0 =>
[...]
<b>...</b>
)
</pre>``` Wrapping it up! #
 
---------------
So you should be well on your way to geeking with Twitter and Yii now. If I've left anything out or if you're confused or my writing sucks, please let me know. I love feedback! jablan 'at' pogostick.com or PM me here.
4 1
12 followers
Viewed: 33 146 times
Version: 1.1
Category: Tutorials
Tags: twitter
Written by: lucifurious
Last updated by: wei
Created on: Jun 11, 2009
Last updated: 13 years ago
Update Article

Revisions

View all history