简体   繁体   中英

Where to put app initialisation code in laravel

I'm creating an app that uses the facebook php sdk, and it requires some config:

require_once("facebook.php");

  $config = array(
      'appId' => 'YOUR_APP_ID',
      'secret' => 'YOUR_APP_SECRET',
      'fileUpload' => false, // optional
      'allowSignedRequest' => false, // optional, but should be set to false for non-canvas apps
  );

  $facebook = new Facebook($config);

Where do I put this so that I can use $facebook in my models and controllers?

In this case you better use the Laravel IoC container.

Create a Service Provider

<?php

require_once("facebook.php");

use Illuminate\Support\ServiceProvider;

class FacebookServiceProvider extends ServiceProvider {

    public function register()
    {
        $app = $this->app;

        $app->bind('facebook', function() 
        {
            $config = array(
              'appId' => 'YOUR_APP_ID',
              'secret' => 'YOUR_APP_SECRET',
              'fileUpload' => false, // optional
              'allowSignedRequest' => false, // optional, but should be set to false for non-canvas apps
            );

            return new Facebook($config);
        });
    }

}

Add it to your app/config/app.php

'FacebookServiceProvider',

And now, anywhere in your application, you have access to it by doing:

App::make('facebook')->whateverMethod();

If you need it to instantiate only once, you can use a singleton:

$app->singleton('facebook', function() 
{
     ....
}

您可以将其放在app / controllers / BaseController.php中,但是我不建议您在模型中使用它,因为它们应严格仅以编程方式表示数据。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM