0

In laravel , I do

composer require facebook/graph-sdk

and it's done, but how to register this package in laravel project after this?

I know i have to go to app.php and change

'providers' => [...

and

'aliases' => [....

but how do I know what to append? How can I get it when I install other packages?

I hope I can do

use Facebook;

in the controller, but I don't know how to.

黃皓哲
  • 3,422
  • 2
  • 7
  • 13
  • As mentioned in this post https://stackoverflow.com/questions/42945596/how-to-integrate-facebook-php-sdk-with-laravel-5-4 you can manually register Facebook sdk. – Amandeep Singh Jul 09 '18 at 11:35
  • @J.Doe That’s a complete lie, given I’ve done so in multiple Laravel applications in the past, and have just posted an answer with an example of how to do exactly that. – Martin Bean Jul 09 '18 at 11:45

1 Answers1

3

The Facebook Graph SDK is just a generic PHP SDK. You’ll want to create a service provider in your Laravel application that binds its configuration values.

First, create environment variables named FACEBOOK_CLIENT_ID and FACEBOOK_CLIENT_SECRET.

Next, bind those environment variables to configuration values. Open your config/services.php file and add the following:

'facebook' => [
    'client_id' => env('FACEBOOK_CLIENT_ID'),
    'client_secret' => env('FACEBOOK_CLIENT_SECRET'),
],

Now, use Artisan to create a service provider (php artisan make:provider FacebookServiceProvider) and add it to the providers array in config/app.php.

The service provider should look like this:

use Facebook\Facebook;

class FacebookServiceProvider extends ServiceProvider
{
    protected $defer = true;

    public function register()
    {
        $this->app->singleton(Facebook::class, function ($app) {
            return new Facebook([
                'app_id' => $app['config']['services.facebook.client_id'],
                'app_secret' => $app['config']['services.facebook.client_secret'],
                'default_graph_version' => 'v2.10',
            ]);
        });
    }

    public function provides()
    {
        return [
            Facebook::class,
        ];
    }
}

This adds a configured instance of the Facebook Graph SDK to your application’s container, meaning you can type-hint it in your classes’ constructors and use it:

class SomeController extends Controller
{
    private $facebook;

    public function __construct(Facebook $facebook)
    {
        $this->facebook = $facebook;
    }

    public function someMethod()
    {
        // Can use $this->facebook and it’ll already be
        // configured with app ID and secret.
    }
}

The service provider is also deferred, meaning the SDK is only loaded when you request it.

Martin Bean
  • 38,379
  • 25
  • 128
  • 201