容器是用來更方便的管理類依賴及運行依賴注入的工具。
依賴注入其實本質上是指在構造函數中對其他需要使用的類迅速實例化。
依賴注入的類統一由容器進行管理,你可以隨時綁定類到容器中,支持多種綁定方式。
例如我們有個 Settings類,現在綁定到容器中
// 綁定類庫標識
bind('settings','app\admin\controller\Settings');
或者:
bind('settings',Settings::class);
或者:
Container::getInstance()->bind('settings', Upgrade::class)
調用方式:
halt(app('settings')->upgradeTask($this->request));
或:
Container::getInstance()->make('settings')->upgradeTask($this->request)
在容器中他會自動調用
/**
* 獲取當前容器的實例(單例)
* @access public
* @return static
*/
public static function getInstance()
{
if (is_null(static::$instance)) {
static::$instance = new static;
}
if (static::$instance instanceof Closure) {
return (static::$instance)();
}
return static::$instance;
}
然後我們用app()助手函數直接獲取類中方法upgradeTask:
app('settings')->upgradeTask($this->request)
綁定閉包
可以綁定一個閉包到容器中
bind('sayHello', function ($name) {
return 'hello,' . $name;
});
綁定實例
也可以直接綁定一個類的實例
$cache = new think\Cache;
// 綁定類實例
bind('cache', $cache);
綁定至接口實現
對於依賴注入使用接口類的情況,我們需要告訴系統使用哪個具體的接口實現類來進行注入,這個使用可以把某個類綁定到接口
// 綁定think\LoggerInterface接口實現到think\Log
bind('think\LoggerInterface','think\Log');