Facebook Sdk For Yii2

Hello everyone,

I’m new here. I want to add Facebook sdk in yii2, normally i did in php was just include facebook.php on top of php file and create $facebook object. Can anyone please help me with that?

You can do it the same way.

But where can I include it to, to be able to call the $facebook object in the entire app?

The best way is to wrap it into an object or include it when needed.

You can call the Facebook SDK class with proper namespaces (copy all the SDK files to a directory) and try.

Alternatively, a simpler direct approach can be to use my yii2-social module. With this extension, you can refer the FB SDK API simply like this:

// fetch the facebook sdk api

$facebook = Yii::$app->getModule('social')->getFbApi();

// Get User ID

$user = $facebook->getUser();

You need to setup the module like this (refer the docs for more details). You can also check the source code to understand more details.

'modules' => [

    'social' => [

        // the module class

        'class' => 'kartik\social\Module',

       // the global settings for the facebook plugins widget

        'facebook' => [

            'appId' => 'FACEBOOK_APP_ID',

            'secret' => 'FACEBOOK_APP_SECRET',




There are other built in social plugins available as Yii widgets if you want to have a look.

Kartik, I gave your social module a try and was up and running in less than 5 minutes. This is a very easy to use and useful module. Nice documentation. It makes Yii 2.0 a lot of fun to work with…

@Kartik, Can I use yii2-social module with multiple apps in facebook? I would like manage multiple apps in my yii system.


You can use yii2-social module with multiple Facebook apps this way:

$social = Yii::$app->getModule('social');

$social->facebook = [

    'appId' => 'YOUR_APP_ID',

    'secret' => 'YOUR_SECRET',

    // any other custom settings


// fetch the facebook sdk api

$facebook = $social->getFbApi();

Thanks @Kartik, this code is what I was looking for.