![](/img/trans.png)
[英]Laravel How to register a ServiceProvider within other ServiceProvider
[英]ServiceProvider register a services with construct params in laravel 5.1
我使用了laravel 5.1,我有這個問題。
在我的AppServiceProvider.php注冊方法中
$this->app->singleton('PingppServices', function ($app, $params) {
return new \App\Services\PingppServices($params['sid']);
});
在PingppServices.php中
private $sid;
public function __construct($params)
{
$this->sid = $params['sid'];
}
public function foo()
{
echo $this->sid;
}
在控制器中我用它來調用它
$pingppServices = app('PingppServices', ['sid' => 1]);
$pingppServices->foo();
所以我的問題是,在laravel 5.0中,我可以像這個app('PingppServices', 1);
,在5.1中,第二個參數必須是一個數組。 我看到app()方法沒有變化,那么有什么變化?
這是使用構造參數解決服務的正確方法嗎?
謝謝。
很難說,沒有對類的目的的洞察和對整個代碼的概述。
一般來說,我傳遞給類的構造函數的東西主要是依賴項和配置變量。 與運行時數據相關的任何內容都應該具有單獨的setter,或者應該作為參數傳遞給需要的方法。
就像我很傷心,沒有更多的洞察力,很難說。
例:
class Foobar {
private $pingppService;
public function __construct(PingppServices $pingppService) {
$this->pingppService = $pingppService;
}
public function wtf() {
$this->pingppService->setParams(Request::all());
$this->pingppService->foo();
}
}
不像你說的那樣,在Laravel 5.1中,app()方法是
/**
* Get the available container instance.
*
* @param string $make
* @param array $parameters
* @return mixed|\Illuminate\Foundation\Application
*/
function app($make = null, $parameters = [])
{
if (is_null($make)) {
return Container::getInstance();
}
return Container::getInstance()->make($make, $parameters);
}
最后,它將調用函數build($concrete, array $parameters = [])
。
所以,第二個參數必須是一個數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.