ソースを参照

Lesson 25: service providers explained.

Frederic G. MARAND 7 年 前
コミット
ead6c1663b
2 ファイル変更21 行追加8 行削除
  1. 16 1
      app/Providers/AppServiceProvider.php
  2. 5 7
      routes/web.php

+ 16 - 1
app/Providers/AppServiceProvider.php

@@ -2,11 +2,18 @@
 
 namespace App\Providers;
 
+use App\Billing\Stripe;
 use App\Post;
+use Illuminate\Foundation\Application;
 use Illuminate\Support\ServiceProvider;
 
 class AppServiceProvider extends ServiceProvider
 {
+    const STRIPE = 'billing.stripe';
+    const STRIPE_KEY = 'services.stripe.key';
+
+    protected $defer = true;
+
     /**
      * Bootstrap any application services.
      *
@@ -26,6 +33,14 @@ class AppServiceProvider extends ServiceProvider
      */
     public function register()
     {
-        //
+        // Use app->singleton(Stripe::class) instead to obtain a reused instance.
+        // Use app->instance(Stripe::class, $stripe) to replace the instance with another object.
+
+        $app2 = $this->app;
+        $this->app->bind(Stripe::class, function (Application $app) use($app2) {
+            // Yes, there are 3 ways to get to the app in a service closure.
+            return new Stripe($this->app['config'][static::STRIPE_KEY]);
+        });
+        $this->app->alias(Stripe::class, static::STRIPE);
     }
 }

+ 5 - 7
routes/web.php

@@ -21,17 +21,15 @@
 */
 
 use App\Billing\Stripe;
+use App\Providers\AppServiceProvider;
 
-// Use singleton() instead to obtain a reused instance.
-// Use instance(Stripe::class, $stripe) to replace the instance with another object.
-App::bind(Stripe::class, function () {
-    return new Stripe(config('services.stripe.key'));
-});
+// Can use either the class name or a readable service name, thanks to aliasing.
+$stripe = App::make(AppServiceProvider::STRIPE);
+$stripeAgain = app(AppServiceProvider::STRIPE);
 
-$stripe = App::make(Stripe::class);
-$stripeAgain = app(Stripe::class);
 $stripeAlso = resolve(Stripe::class);
 $stripeToo = app()->make(Stripe::class);
+
 dd($stripe, $stripeAgain, $stripeAlso, $stripeToo);
 
 /** @var \Illuminate\Routing\Router $this */