Create facebook application using php – Yii Framework and Graph API

Recently we developed an facebook application and during the development of application, we encounter lots of issues due to vague Facebook documentation. We wanted to share our experience so that other developers can develop facebook application easily. We have used yii framework for this application as its pretty cool framework and application development on this framework takes less time without compromising the performance.In this article, we assume that the reader have experience in facebook application development.

A little introduction about yii framework

Yii is a high-performance PHP framework best for developing Web 2.0 applications. Yii comes with rich features: MVC, DAO/ActiveRecord, I18N/L10N, caching, authentication and role-based access control, scaffolding, testing, etc. It can reduce your development time significantly. It has pretty good documentation and you can get more help by googling the issue. You can also compare the performance of yii framework with other popular frameworks here

A little introduction about facebook Graph API

Facebook introduced new components of Facebook Platform and one of them is Graph API. The API provides access to Facebook objects like people, photos, events etc. and the connections between them like friends, tags, shared content etc. via a uniform and consistent URI to access the representation. Every object can be accessed using the the URL https://graph.facebook.com/ID, where ID stands for the unique ID for the object in the social graph. For more details, please take a look at graph api

Sample facebook application using yii framework

We assume that you have created facebook application and have the access to the App Id and Secret Key for the application. If you have no idea about it then please take a look at the links below to get started. We also assume that you have also created the sample application using yii framework.

Configure facebook api in the application

Get php facebook api from git and place it in the vendors directory(create if not exist). We needed some additional properties so we created facebookwrapper which extends facebook api.

require 'facebook.php';
/*
 * Created on Mar 15, 2011
 *
 * Provides access to Custom application properties along with the Facebook Platform.
 *
 * @author makeurownrules 
 */
 class FacebookWrapper extends Facebook{
 ...
 ...
 }

We had initialize the facebook api in the controller and added facebook filter to verify that the facebook session exist. We need to include the wrapper in the main controller in the components package.

Yii::import('application.vendors.*');
require_once('facebook-php-sdk-b14edfa/src/facebookwrapper.php');
...
...
function __construct($id,$module=null) {
    parent::__construct($id, $module);
    // Get an instance of the Facebook class distributed as the PHP SDK by facebook:
    Yii::app()->params['facebook'] = new FacebookWrapper(array(
      'appId'  => 'appId',
      'secret' => 'secretKey',
      'cookie' => true,
      'appName' => 'App Name',
      'canvasPage' => 'http://apps.facebook.com/appname/',
      'canvasUrl'  => 'http://example.com/appname/'
      ));

  }

  /**
   * Filters for all the request coming to facebook application
   */
  public function filters() {
    return array(
            'facebook',
    );
  }

  public function filterFacebook($filterChain) {
    header('P3P: CP="CAO PSA OUR"');
    $facebook = Yii::app()->params['facebook'];
    $session = $facebook->getSession();
    $fbme = null;
    if ($session) {
      try {
        $uid = $facebook->getUser();
        $fbme = $facebook->api('/me');
      } catch (FacebookApiException $e) {
         //handle error
      }
    }
    if ($fbme) {
      // call $filterChain->run() to continue filtering and action execution
      $filterChain->run();
    }
    else {
      $appId = $facebook->getAppId();
      $canvasUrl = $facebook->getCanvasPage();
      // Set the required permissions for the application
      $perms = "publish_stream,friends_birthday, offline_access, email";
      $loginUrl = "https://www.facebook.com/dialog/oauth?scope=".$perms.
        "&client_id=".$facebook->getAppId().
        "&redirect_uri=".urlencode($canvasUrl);
      location =  'top.location.href=';
     echo(""); Yii::app()->end(); } }

After initializing the facebook API, we can access facebook instance in the SiteController or any other controller.

public function actionIndex()
	{
		$facebook = Yii :: app()->params['facebook'];
                $myuid = $facebook->getUser();
	  // renders the view file 'protected/views/site/index.php'
		// using the default layout 'protected/views/layouts/main.php'
		$this->render('index',array('myuid'=> $myuid));
	}

So facebook api can be accessed and used to publish on wall, send message or change the status of user.

Source code and Demo

Source for sample application is available here.
Demo is available here

References

We highly recommend to go through basic facebook application documentation.

Official Facebook documentation / developer site:
Facebook Developers Site

Facebook tutorials:
publish post with media on wall using facebook Graph API

Facebook PHP Tutorial
Developing with the Facebook Platform and PHP

Create facebook application using php – Yii Framework and Graph API was last modified: April 11th, 2016 by Kapil Jain