OOP Use Case for Flickr

By ryan, January 17, 2015

Setting up my site and integrating with my flickr account – I noticed the rather procedural methods to the flickr api. Below is the sample provided by flickr:

#
# build the API URL to call
#

$params = array(
	'api_key'	=> '81e7e11aeac57ac668609d316f6388ce',
	'method'	=> 'flickr.photos.getInfo',
	'photo_id'	=> '251875545',
	'format'	=> 'php_serial',
);
 
$encoded_params = array();
 
foreach ($params as $k => $v){
 
	$encoded_params[] = urlencode($k).'='.urlencode($v);
}
 
 
#
# call the API and decode the response
#

$url = "https://api.flickr.com/services/rest/?".implode('&', $encoded_params);
 
$rsp = file_get_contents($url);
 
$rsp_obj = unserialize($rsp);
 
 
#
# display the photo title (or an error if it failed)
#

if ($rsp_obj['stat'] == 'ok'){
 
	$photo_title = $rsp_obj['photo']['title']['_content'];
 
	echo "Title is $photo_title!";
}else{
 
	echo "Call failed!";
}

This was just the example provided to give you an idea of usage. From this – I now understand the basic concept of params that are passed and which are shared and such.

All calls have the same URL but pass different parameters. All API calls also require an api_key (this is user based).

Below I created a class to get all photos from a photoset on flickr. You can see how I found the similarities and attempted to create a uniform return and less code that can do more and grow easier.

class Flickr{
	protected $api_key;
	const API_URL = "https://api.flickr.com/services/rest/?";
 
	public function __construct(){
		$this->api_key = '8d4a295115d687f87587f3b39b4fdd7e'; 
	}
	public function getPhotosBySet($set_id, $per_page = 30){
		$params = array(
			'method'	=> 'flickr.photosets.getPhotos',
			'photoset_id'	=> $set_id,
			'per_page' => $per_page,
		);
		$rsp_obj = $this->_callService($params);
		$photo_collection = array();
		foreach($rsp_obj['photoset']['photo'] as $photo){
			//print_r($photo); 
			$params = array(
				'method'	=> 'flickr.photos.getInfo',
				'photo_id'	=> $photo['id'],
				'secret' => $photo['secret'],
			);
			$photodata = $this->_callService($params);
			$photo_collection[] = $photodata['photo'];
			//print_r($photodata);
		}
		return $photo_collection;
	// 	print_r($photo_collection);
 
	}
	protected function _callService($params){
		$encoded_params = array();
		$params['format'] = 'php_serial';
		$params['api_key'] = $this->api_key;
		foreach ($params as $k => $v){
			$encoded_params[] = urlencode($k).'='.urlencode($v);
		}
		$url = self::API_URL . implode('&', $encoded_params);
		$rsp = file_get_contents($url);
		if($this->_success($rsp)) return unserialize($rsp);
		else return false;
	}
	protected function _success($rsp){
		$rsp = unserialize($rsp);
		if($rsp['stat'] == 'ok') return $rsp;
		else return false;
	}
}
 
$flickr_connector = new Flickr;
$flickr_connector->getPhotosBySet(FLICKR_PHOTOSET_ID); 
// Returns array of images
// and their info based on photoset_id