php - 請問服務容量的綁定初始數據具體如何實現
ringa_lee
ringa_lee 2017-04-10 17:58:09
0
2
287

服務容量的綁定初始數據的具體如何實現?
官方文檔寫得太精簡了,完全看不明白。

$this->app->when('App\Http\Controllers\UserController')
          ->needs('$variableName')
          ->give($value); 

能不能麻煩貼下具體的代碼。
另外,綁定初始數據是為了在其它位置傳值給類的構造函數嗎?如果不是,請問如何在服務容量中傳值給類的構造函數。
非常感謝!!

ringa_lee
ringa_lee

ringa_lee

répondre à tous(2)
巴扎黑

首先,我们并不是一定要通过$this->app->xxx的方式来绑定实例到容器。方法有很多。
这样

$this->app->singleton('FooBar', function ($app) {
    return new FooBar($app->make('HttpClient'));
});

这样

$api = new HelpSpot\API(new HttpClient);
$this->app->instance('HelpSpot\Api', $api);

还有这样

$this->app->bind('HelpSpot\API', function ($app) {
    return new HelpSpot\API($app->make('HttpClient'));
});

綁定初始數據是為了在其它位置傳值給類的構造函數嗎

不是。提供初始数据是为了把参数传给我们要注入到容器里面的类构造函数

請問如何在服務容量中傳值給類的構造函數

如上面第二段代码所示,我们将new HttpClient这个参数,传给了HelpSpotAPI类的构造函数,另外两个例子也差不多。

如果还没解答到你的疑惑,请继续追问

参见:http://laravelacademy.org/pos...

大家讲道理

叫服务容器……

看这个slide吧:Learn to Stop Wiring and Love Laravel's Container

Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!