Saturday, March 12, 2011

Merging Facebook SDK with CodeIgniter 2.0

Merging the Facebook PHP SDK with CodeIgniter turned out to be not so simple of a task, due to the fact that no one at all has tried documenting how to do it in SDK 2.1.x and with CI 2.0, so because none have tried I am now here to show you all how, instead of being greedy.

What you need is the facebook php sdk which you can download at GitHub (https://github.com/facebook/php-sdk/) and CodeIgniter 2.0 (http://codeigniter.com).

First off you need to have set up an application, which you have probably done via multiple sites prior to me, so for now I will assume you have an app registered with facebook. Just make sure you use the iframe system, because FBML is being deprecated and will eventually be phased out.

Secondly, you need to uncompressed and upload CI2.0 to your server, and setup all the configurations the way you need them. I use Request_URI for mine.

After that, uncompress the facebook-php sdk and look in the folder /src and grab the facebook.php in there, and move it to the /application/libraries folder of your CI installation, after which rename it to Facebook.php to ensure compatibility with CI lib class.

Now came the fun part.

Unfortunately unlike a lot of other tutorials say you can just create a config file for facebook, well that was for the modified and butchered versions of the facebook api. I am going to show you how to pull up facebook api unaltered and with complete support of both. Took me over an hour or so tweaking it to work.

In the controller you want to load the facebook api, find the __constructor() and place:
function __construct()
{
parent::__construct();

$params['appId'] = 'your_app_id';
$params['secret'] = 'your_app_secret';
$params['cookie'] = true;
$this->load->library('facebook', $params);

}
This will allow you to use facebook as $this->facebook->api() and other functions. Such as what I use in the __construct() right after the load->library event:
$this->fb_session = $this->facebook->getSession();
$this->fb_me = null;
// Session based API call.
if ($this->fb_session) {
try {
$this->fb_uid = $this->facebook->getUser();
$this->fb_me = $this->facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
}
}
$this->fb_appid = $this->facebook->getAppId();
I personally use $this->fb_* in order to make sure that I don't accidentally use the same name as a variable previously declared in the system.

Hope this helps you guys, looking for a solution like I was. :)

No comments:

Post a Comment