TP的依赖注入:将类类型的对象作为参数注入到当前类中
生活随笔
收集整理的這篇文章主要介紹了
TP的依赖注入:将类类型的对象作为参数注入到当前类中
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
思想
依賴注入其實本質上是指對類的依賴通過構造器完成自動注入,
例如在控制器架構方法和操作方法中一旦對參數進行對象類型約束則會自動觸發依賴注入,
由于訪問控制器的參數都來自于URL請求,普通變量就是通過參數綁定自動獲取,對象變量則是通過依賴注入生成。
<?php namespace app\controller;use think\Request;class Index {protected $request;public function __construct(Request $request){$this->request = $request;}public function hello($name){return 'Hello,' . $name . '!This is '. $this->request->action();} }構造方法實例化
$foo = new Foo($bar);$foo = invoke('Foo');普通方法實例化
$result = invoke(['Foo', 'bar']);?手動綁定類:前面是名字? 后面是真實的類文件
$this->app->bind('think\Cache', 'app\common\Cache'); bind('cache', 'think\Cache');手動綁定對象
$cache = new think\Cache; // 綁定類實例 bind('cache', $cache);全局綁定provider.php
<?php use app\ExceptionHandle; use app\Request;// 容器Provider定義文件 return ['think\Request' => Request::class,'think\exception\Handle' => ExceptionHandle::class, ];TP很多內置的綁定
類的實例化使用
$app = app(); // 判斷對象實例是否存在 isset($app->cache);// 注冊容器對象實例 $app->cache = think\Cache::class;// 獲取容器中的對象實例 $cache = $app->cache;?
總結
以上是生活随笔為你收集整理的TP的依赖注入:将类类型的对象作为参数注入到当前类中的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 斯柯达明锐喇叭保险丝在哪个位置
- 下一篇: 五菱宏光车窗升降不了怎么短接开关使玻璃应