Using the Bit.ly v.3 API with Zend Framework

Aug 3, 2010   #bitly  #php  #zend framework 

I recently looked at providing a URL-shortening service for our new sharing module. Right now, my needs are very minimal, so I decided to write a class (currently using static methods) that utilizes Zend_Http_Client to communicate with Bit.ly API service.

Here’s my code:

<?php
class My_UrlShorten {

	const bitlyLogin = ''LOGIN''; //Your Bit.ly login here
	const bitlyApiKey = ''API_KEY''; //Your api key here

	/**
	 * Returns a URL shortened using the Bit.ly service
	 * @param string $url
	 * @return string
	 */
	public static function bitly($url) {
		$client = new Zend_Http_Client(''http://api.bit.ly/v3/shorten'');
		$client->setParameterGet(array(
				''login'' => self::bitlyLogin,
				''apiKey'' => self::bitlyApiKey,
				''longUrl'' => $url
		));

		$response = $client->request();
		if ($response->isSuccessful()) {
			$results = Zend_Json::decode($response->getBody());
			if ($results[''status_txt''] == ''OK'' && isset($results[''data''][''url''])) {
				return $results[''data''][''url''];
			}
		}
		return '''';
	}
}

I may add more Bitly methods as I need them, but this provides me with all of the functionality I currently need. I also probably don’t need to use the Zend_Json class since I never use anything less than PHP 5.2, but I figure that it probably doesn’t have too much of a hit since Zend_Json will use json_decode if it’s available.

To use the new class:

<?php
$url = ''http://myurl.com'';
$shortened = My_UrlShorten::bitly($url);