how CodeIgniter Facebook SDK 4 with Composer

 

Questions


I’m trying to install and run the Facebook SDK on CodeIgniter using Composer.

CodeIgniter is installed and working nicely.

Composer support was added by doing the following:

  • curl -s http://getcomposer.org/installer | php
  • touch composer.json
  • Added the require lines to the composer.json file ("facebook/php-sdk-v4" : "4.0.*")
  • Ran composer update

All went to plan. Composer created a /vendor folder, and the Facebook SDK is there.

I then added Composer support to CodeIgniter by adding the line include_once './vendor/autoload.php'; to the top of index.php.

No errors at this point.

I’m now looking to call the SDK. I don’t seem to be able to use any of the Facebook classes though. See below for things tried and failed…


var_dump(class_exists('Facebook')); shows bool(false)


FacebookSession::setDefaultApplication('app id removed', 'app secret removed');

Spits out:

Fatal error: Class 'FacebookSession' not found in /var/sites/***/public_html/application/controllers/welcome.php on line 13


And a more full example:

<?php
class Welcome extends CI_Controller {

    use FacebookFacebookSession;
    use FacebookFacebookRequest;
    use FacebookGraphUser;
    use FacebookFacebookRequestException;

    public function index()
    {           
        FacebookSession::setDefaultApplication('app id removed', 'app secret removed');

    }
}

Spits out:
Fatal error: Welcome cannot use FacebookFacebookSession - it is not a trait in /var/sites/***/public_html/application/controllers/welcome.php on line 5

 

 

————————————————-

Answer

You’ve mixed the position of the USE statement.
What you might do is to declare the classes from the FB SDK outside and before class, and not inside. By using Use inside a class you are pointing to trait functionality, which should be included into the class.

<?php
class MyClass extends MyBaseClass {
    // this is a namespaced trait inside the class
    // = extend class with trait
    use SomeWhereTrait; 
}
?>

<?php
// this is the declaration of a namespaced class outside of the class    
use SomeWhereClass; 

class MyClass extends MyBaseClass
{
    public function helloWorld()
    {  
        $c = new Class;
        // ...
    }
}
?>

Your code becomes:

<?php
use FacebookFacebookSession;
use FacebookFacebookRequest;
use FacebookGraphUser;
use FacebookFacebookRequestException;

class Welcome extends CI_Controller {

    public function index()
    {           
        FacebookSession::setDefaultApplication('app id removed', 'app secret removed');

    }
}

codeigniter,facebook,facebook-graph-api,facebook-sdk-4.0,php

Facebook Comments

Post a comment