依賴注入
ThinkPHP的依(yi)(yi)(yi)賴(lai)注入(ru)(也稱(cheng)之為(wei)控(kong)(kong)制(zhi)(zhi)反轉)是一種較為(wei)輕量的實(shi)現,無需任(ren)(ren)何的配置(zhi),并且主要針(zhen)對訪(fang)問控(kong)(kong)制(zhi)(zhi)器(qi)進行依(yi)(yi)(yi)賴(lai)注入(ru)。可以(yi)在控(kong)(kong)制(zhi)(zhi)器(qi)的構造(zao)函數或者操作方法(fa)(指訪(fang)問請求的方法(fa))中(zhong)類型(xing)(xing)聲明任(ren)(ren)何(對象類型(xing)(xing))依(yi)(yi)(yi)賴(lai),這些依(yi)(yi)(yi)賴(lai)會被自動解析并注入(ru)到控(kong)(kong)制(zhi)(zhi)器(qi)實(shi)例或方法(fa)中(zhong)。
自動注入請求對象
架構方法注入
在控制器(qi)的架構方(fang)法中會自動注入當前請(qing)求(qiu)對象,例如(ru):
namespace app\index\controller;
use think\Request;
class Index
{
protected $request;
public function __construct(Request $request)
{
$this->request = $request;
}
public function hello()
{
return 'Hello,' . $this->request->param('name') . '!';
}
}
操作方法注入
控制器的操作方法中如果需要調用請求對象Request的話,可以在方法中定義Request類型的(de)參數(shu),并且參數(shu)順序無關,例如:
namespace app\index\controller;
use think\Request;
class Index
{
public function hello(Request $request)
{
return 'Hello,' . $request->param('name') . '!';
}
}
訪問URL地址的時候 無需傳入request參數,系統會自動注入當前的Request對象實例到該參數。
如果繼承了系統的Controller類的話,也可以直接調用request屬性,例如:
<?php
namespace app\index\controller;
use think\Controller;
class Index extends Controller
{
public function hello()
{
return 'Hello,'.$this->request->param('name');
}
}
其它對象自動注入(V5.0.1)
從5.0.1版本開始,控制器的(de)(de)架(jia)構方(fang)法(fa)(fa)和操作(zuo)方(fang)法(fa)(fa)支持任意對象的(de)(de)自動(dong)注入(ru)。
架構方法注入
namespace app\index\controller;
use app\index\model\User;
use think\Request;
class Index
{
protected $request;
protected $user;
public function __construct(Request $request, User $user)
{
$this->request = $request;
$this->user = $user;
}
}
對于已經進行了綁定(屬性注入)的對象,即可自動完成依賴注入,如果沒有進行對象綁定的話,會自動實例化一個新的對象示例傳入(如果類定義有
instance方法,則會自動調用instance方法進行實例化)。
架構方法的依賴(lai)注入(ru)不影響其它類型(xing)的參數綁定。
操作方法注入
我們把User模型綁定到當前(qian)請求對(dui)象:
Request::instance()->bind('user', \app\index\model\User::get(1));
然后就(jiu)可以在操作方法中進行對象(xiang)參(can)數的自動注入,代碼:
<?php
namespace app\index\controller;
use app\index\model\User;
use think\Controller;
class Index extends Controller
{
public function hello(User $user)
{
return 'Hello,'.$user->name;
}
}
如果沒有事先在Request對象中進行對象綁定的話,調用hello方法的時候user參數(shu)會自(zi)動(dong)實例化,相(xiang)當于完成了下(xia)面的綁定操作:
Request::instance()->bind('user', new \app\index\model\User);
對象自動(dong)注入(ru)不影(ying)響原(yuan)來的參數綁定。
invoke方法自動調用(v5.0.2)
5.0.2版本開始,如果依賴注入的類有定義一個可調用的靜態invoke方(fang)法,則會自(zi)動調用invoke方(fang)法完成依(yi)賴注入的自(zi)動實(shi)例(li)化(hua)。
invoke方法的參數是當前請求(qiu)對象實例,例如:
namespace app\index\model;
use think\Model;
class User extends Model
{
public static function invoke(Request $request)
{
$id = $request->param('id');
return User::get($id);
}
}
