Using the Factory Method Pattern in PHP 5, a Quick Example

Place your factory classes & interface inside a directory of your choice, like /api/YOUR-PATH-TO-CLASSES-HERE/. Just make sure to specify that path in the __autoload() method when you use the factory (see the last code example below).

Set up the Interface

<?
interface IApiGrabr
{
	public function callApi();
}
?>

Implement the Interface with a Twitter Class

This code assumes there’s a directory named ‘api’ at your server’s public root folder. Also, note, in a live example you might want to have a separate file to store some of your Twitter, etc credentials. The Twitter oAuth library I’m using can be found on github.

<?
class TwitterApiGrabr implements IApiGrabr 
{
	public function callApi(){

		require_once('/api/twitteroauth.php'); //open source class from github

		$connection = new TwitterOAuth('your-consumer-key', 
		                               'your-consumer-secret', 
		                               'your-access-token-here',
		                               'your-access-token-secret-here');

		$content = $connection->get('account/rate_limit_status');
		
		// you can now call all the methods on the twitteroauth/connection object
		$user = $connection->get('account/verify_credentials');

		$favs = $connection->get('favorites',  array(
			  'screen_name'      => 'TechCrunch',
			  'count'            => 11,
		));

		//this is FPO, in real life write some formatted display code:
                var_dump($favs);
	}
}
?>

Implement the Interface with an Instagram Class

The below code uses a handy open source Instagram oAuth class from github.

<?
class InstagramApiGrabr implements IApiGrabr 
{
	public function callApi(){

		//open source class from github
		require_once('/api/Instagram.php'); 

		$instagram = new Instagram('your-client-id-here', 'your-client-secret-here', 'your-access-token-here');
		
		//simplified call, in real life, there should be an authentication check (see Instagram.php example on github)		  
	    try {
	        $instafeed = $instagram->get('users/self/media/liked'); 
	    }catch(InstagramApiError $e) {
	        die($e->getMessage());
	    }
		
	    //FPO JSON display, in real life, you'd format this w/ HTML, probably via a for loop	
        echo '<p>&nbsp;</p>'.json_encode($instafeed);
	}
}
?>

Implement the Interface with a Tumblr Class

<?
class TumblrApiGrabr implements IApiGrabr 
{
	public function callApi(){
		//posts
		$pth2 = 'http://api.tumblr.com/v2/blog/YOUR-TUMBLR-NAME-HERE.tumblr.com/posts/photo?api_key=YOUR-API-KEY-HERE';	

		///Tumblr account's posts - http://www.tumblr.com/docs/en/api/v2#posts
		$pthresult2 = file_get_contents($pth2);
		
		//FPO to just display raw JSON response, in real life, you'd format it with HTML
		echo $pthresult2;	
	}
}
?>

Set up your Factory class

<?
class MyFactory
{ 
  private static $dictionary;

  public static function init()
    {
      self::$dictionary = array('instagram' => new InstagramApiGrabr(), 
                         'twitter' => new TwitterApiGrabr(), 
                         'tumblr' => new TumblrApiGrabr());
    }

    public static function GetApi($param='instagram')
    {
        return self::$dictionary[$param]; 
    } 
}
?>

Use Your Factory Class Like So

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <title>API Test</title>
</head>
<body>
<?
  //allow PHP to auto include your individual class files as needed 
  function __autoload($class_name) {
      require_once('/api/YOUR-PATH-TO-CLASSES-HERE/'.$class_name . '.php');
  }
  
  MyFactory::init();

  /// control the below factory method calls via drop down menu, page navigation inside a carousel, etc. 

  //will spit out the Instagram JSON feed
  $a = MyFactory::GetApi('instagram');
  $a->callApi(); 

  //will spit out the Twitter JSON feed
  $a = MyFactory::GetApi('twitter');
  $a->callApi();

  //will spit out the Tumblr JSON feed
  $a = MyFactory::GetApi('tumblr');
  $a->callApi();
?>
</body>
</html>

Side Note on the Code Igniter framework and PHP interfaces

The Code Igniter mvc framework for PHP doesn’t seem to support “interface” or “implements” key words as of version 2.1.3.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s