CakePHP and facebook SDK as Vendor

Published on : July 28, 2011

Author:

Category: Our Blog


For most of the application on Facebook is simple but sometimes you have such a big application to develop you need to use a php framework. As I am a CakePHP developer, I like to use CakePHP for these type of applications .In this How-To, I will show how you can add Facebook SDK in CakePHP .

First create an application on Facebook. You can do it here. Then download the official SDK from github. Now Create a folder in vendors named “facebook”. Put the base_facebook.php,facebook.php and fb_ca_chain_bundle.crt on that folder. Now you add the details of The app to bootstrap.php.


Configure::write("FB_APP_ID", 'you app id');
Configure::write("FB_APP_SECRET", 'you app secrete');
Configure::write("APP_URL", 'you app url like this http://apps.facebook.com/my-app/');
Configure::write("SITE_URL", 'http://your site url/my-app/');

Now in app_controller.php we add a function checkUserSession() and call this function in beforeFilter()


    function beforeFilter()
    {
        $this->checkUserSession();
    }

    function checkUserSession() {
        if ($this->Session->read('user')=="" ') {
            $this->Session->delete('user');
            $this->redirect('/users/login');
            return false;
        }
        return true;
    }

Now in users_controller.php we develop code for login.


    function login() {
        App::import('Vendor', 'facebook', array('file' => 'facebook/facebook.php'));
        $facebook = new Facebook(array(
          'appId'  => Configure::read("FB_APP_ID"),
          'secret' => Configure::read("FB_APP_SECRET"),
        ));

        if (isset($this->params['url']['code']) and $this->params['url']['code'] !='' ){
            $uid = $facebook->getUser();
            echo "<script type='text/javascript'>top.location.href = '".Configure::read('APP_URL')."';</script>";
            exit;
        }

        $uid = $facebook->getUser();
        if ($uid) {
          try {
            $user_profile = $facebook->api('/me');
          } catch (FacebookApiException $e) {
            $user = null;
          }
        }
        $loginUrl   = $facebook->getLoginUrl(
                array(
                    'scope'         => 'user_about_me,user_birthday,email,publish_stream,offline_access'
                ),''
        );

        if (!$uid) {
            echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
            exit;
        }
        $this->Session->write('user', $uid);
        $this->Session->setFlash('You successfully logged in.', 'flash_success');
        $this->redirect('/home');
    }

That it.Now you call graph api like $facebook->api(‘/me’). Simple. Check my other CakePHP How-tos


Leave a Reply

Your email address will not be published. Required fields are marked *