其實laravel中的服務容器就是一個依賴容器,依賴容器是什麼,請看下文。laravel
當一個系統變複雜後,常常會遇到A類須要B類的方法,B類須要C類的方法這樣的狀況。傳統的思路下,咱們會這麼寫:git
class Bim { public function doSomething() { echo __METHOD__, '|'; } } class Bar { public function doSomething() { $bim = new Bim(); $bim->doSomething(); echo __METHOD__, '|'; } } class Foo { public function doSomething() { $bar = new Bar(); $bar->doSomething(); echo __METHOD__; } } $foo = new Foo(); $foo->doSomething();
應用依賴注入的思想(依賴注入聽上去很花哨,其實質是經過構造函數或者某些狀況下經過 set 方法將類依賴注入到類中):
改爲這樣:github
class Bim { public function doSomething() { echo __METHOD__, '|'; } } class Bar { private $bim; public function __construct(Bim $bim) { $this->bim = $bim; } public function doSomething() { $this->bim->doSomething(); echo __METHOD__, '|'; } } class Foo { private $bar; public function __construct(Bar $bar) { $this->bar = $bar; } public function doSomething() { $this->bar->doSomething(); echo __METHOD__; } } $foo = new Foo(new Bar(new Bim())); $foo->doSomething(); // Bim::doSomething|Bar::doSomething|Foo::doSomething
上面類的實例化仍是咱們手動new的,依賴容器的做用就是把類的實例化管理起來,應用程序須要到Foo類,就從容器內取得Foo類,容器建立Bim類,再建立Bar類並把Bim注入,再建立Foo類,並把Bar注入,應用程序調用Foo方法,Foo調用Bar方法,接着作些其它工做。
上面應用依賴容器後(這段代碼來自Twittee):app
class Container { private $s = array(); function __set($k, $c) { $this->s[$k] = $c; } function __get($k) { return $this->s[$k]($this); } } $c = new Container(); $c->bim = function () { return new Bim(); }; $c->bar = function ($c) { return new Bar($c->bim); }; $c->foo = function ($c) { return new Foo($c->bar); }; // 從容器中取得Foo $foo = $c->foo; $foo->doSomething(); // Bim::doSomething|Bar::doSomething|Foo::doSomething
看看官方的例子:
註冊一個服務:ide
use Riak\Connection; use Illuminate\Support\ServiceProvider; class TestServiceProvider extends ServiceProvider { /** * 在容器中註冊綁定。 * * @return void */ public function register() { //使用singleton綁定單例 $this->app->singleton('test',function(){ return new TestService(); }); } }
有沒有發現register方法其實就是往依賴容器裏設置一個類。而後官方文檔也說了,
$this->app就是一個服務容器,聽名字也知道了其實就是依賴容器。函數