服務(wù)容量的綁定初始數(shù)據(jù)的具體如何實(shí)現(xiàn)?
官方文檔寫得太精簡(jiǎn)了,完全看不明白。
$this->app->when('App\Http\Controllers\UserController')
->needs('$variableName')
->give($value);
能不能麻煩貼下具體的代碼。
另外,綁定初始數(shù)據(jù)是為了在其它位置傳值給類的構(gòu)造函數(shù)嗎?如果不是,請(qǐng)問如何在服務(wù)容量中傳值給類的構(gòu)造函數(shù)。
非常感謝!!
ringa_lee
首先,我們并不是一定要通過$this->app->xxx的方式來綁定實(shí)例到容器。方法有很多。
這樣
$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'));
});
綁定初始數(shù)據(jù)是為了在其它位置傳值給類的構(gòu)造函數(shù)嗎
不是。提供初始數(shù)據(jù)是為了把參數(shù)傳給我們要注入到容器里面的類構(gòu)造函數(shù)
請(qǐng)問如何在服務(wù)容量中傳值給類的構(gòu)造函數(shù)
如上面第二段代碼所示,我們將new HttpClient
這個(gè)參數(shù),傳給了HelpSpotAPI
類的構(gòu)造函數(shù),另外兩個(gè)例子也差不多。
如果還沒解答到你的疑惑,請(qǐng)繼續(xù)追問
參見:http://laravelacademy.org/pos...
叫服務(wù)容器……
看這個(gè)slide吧:Learn to Stop Wiring and Love Laravel's Container
微信掃碼
關(guān)注PHP中文網(wǎng)服務(wù)號(hào)
QQ掃碼
加入技術(shù)交流群
Copyright 2014-2025 http://ipnx.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號(hào)