Twitter model plus plus (for the Twitter DataSource)

by rynop
I've added a few helpful functions to the Twitter model for the Twitter DataSource example in the 1.3 CakePHP Cookbook. Specifically, the auto detection and shrinking of URLs in a string intended for Twitter.
The Cookbook has a great little example for a Twitter DataSource:
I've expanded on the model in the example to add a few helpful methods. Figured I would share it with the world as shrinking URL's for twitter is pretty commonplace today.

Once you are familiar with the CookBook example (link above) my model is really easy to use.

The code and example

First the model: <?php
 * Model for use with Tweet datasource (
 * Requires PHP 5.2+
 * Based on 
 * with help from
 * big ups to and
 * Exmaples:
 * $this->Tweet->find('all');
 * $conditions= array('username' => 'caketest');
 * $otherTweets = $this->find('all', compact('conditions'));
 * $this->save(array('status' => 'This is an update'));
 * @author          rynop
 * @link,
 * @license       MIT License (
class Tweet extends AppModel {
$useDbConfig 'twitter';

     * Convert a URL to a tinyurl
     * @param string $url
     * @return string URL
public function getTinyURL($url){
$conn = new HttpSocket();
     * Post something to your twitter account. Member it truncates at 160.
     * @param string $theTweet
     * @param boolean $shrinkURLs
public function statusUpdate($theTweet,$shrinkURLs=true){
$regex '@((https?://)?([-\w]+\.[-\w\.]+)+\w(:\d+)?(/([-\w/_\.]*(\?\S+)?)?)*)@';
$theTweet preg_replace_callback($regex, array(&$this'createTinyURLCallback'), $theTweet);
Configure::read('debug') == 0$this->save(array('status' => $theTweet));
    private function 

Now an example controller: <?php
class NewsController extends AppController {
$name 'News';
$this->Tweet->statusUpdate('Sites I like -');

In short, what this does is converts the long URLs into ones - automatically.

So why instead of requires api creds, and I don't care about tracking URLS. Plus, consuming the service is a 1 liner and is not resource intensive! (thanks HttpSocket)

Note: If you have a high traffic site - may be better, as I'm guessing they have a batch conversion of a json array of urls (only requires 1 socket connection vs X in my example).

Oh, and if its not posting your tweet to your twitter account, change your debug level in core.php to 0, or rip out the line of code where I check debug level ;)

Hope this helps someone else out.


More on Models



login to post a comment.