W3Cschool
恭喜您成為首批注冊(cè)用戶(hù)
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
幾乎你所有服務(wù)容器將與已注冊(cè)的服務(wù)提供者綁定,這些例子都在情境(context)使用容器做說(shuō)明,如果應(yīng)用程序其它地方需要容器實(shí)例,如工廠(factory),能以類(lèi)型提示 Illuminate\Contracts\Container\Container 注入一個(gè)容器實(shí)例。另外,你可以使用 App facade 訪問(wèn)容器。
在一個(gè)服務(wù)提供者內(nèi)部,你總是可以通過(guò) $this->app 實(shí)例變量來(lái)訪問(wèn)到容器。
在服務(wù)提供者里,總是通過(guò) $this->app 實(shí)例變量使用容器。
服務(wù)容器注冊(cè)依賴(lài)有幾種方式,包括閉包回調(diào)和綁定實(shí)例的接口。首先,我們來(lái)探討閉包回調(diào)的方式。被注冊(cè)至容器的閉包解析器包含一個(gè) key (通常用類(lèi)名稱(chēng)) 和一個(gè)有返回值的閉包:
$this->app->bind('FooBar', function($app)
{
return new FooBar($app['SomethingElse']);
});
有時(shí)候,你可能希望綁定到容器的對(duì)象只會(huì)被解析一次,之后的調(diào)用都返回相同的實(shí)例:
$this->app->singleton('FooBar', function($app)
{
return new FooBar($app['SomethingElse']);
});
你也可以使用 instance 方法,綁定一個(gè)已經(jīng)存在的實(shí)例到容器,接下來(lái)將總是返回該實(shí)例:
$fooBar = new FooBar(new SomethingElse);
$this->app->instance('FooBar', $fooBar);
從容器解析出實(shí)例有幾種方式。
一、可以使用 make 方法:
$fooBar = $this->app->make('FooBar');
二、你可以像「訪問(wèn)數(shù)組」一樣對(duì)容器進(jìn)行訪問(wèn),因?yàn)樗鼘?shí)現(xiàn)了PHP的 ArrayAccess 接口:
$fooBar = $this->app['FooBar'];
最后,也是最重要的一點(diǎn),你可以在構(gòu)造函數(shù)中簡(jiǎn)單地「類(lèi)型指定(type-hint)」你所需要的依賴(lài),包括在控制器、事件監(jiān)聽(tīng)器、隊(duì)列任務(wù),過(guò)濾器等等之中。容器將自動(dòng)注入你所需的所有依賴(lài):
<?php namespace App\Http\Controllers;
use Illuminate\Routing\Controller;
use App\Users\Repository as UserRepository;
class UserController extends Controller {
/**
* The user repository instance.
*/
protected $users;
/**
* Create a new controller instance.
*
* @param UserRepository $users
* @return void
*/
public function __construct(UserRepository $users)
{
$this->users = $users;
}
/**
* Show the user with the given ID.
*
* @param int $id
* @return Response
*/
public function show($id)
{
//
}
}
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: