#### 方法注入
如果你需要通過請求對象來擴展一些用法,可以使用方法注入功能,例如我們需要在當前請求對象中讀取用戶信息,就可以在應用公共文件中添加下面代碼:
~~~
// 通過hook方法注入動態方法
Request::hook('user','getUserInfo');
~~~
getUserInfo函數定義如下
~~~
function getUserInfo(Request $request, $userId)
{
// 根據$userId獲取用戶信息
return $info;
}
~~~
要注入的方法的第一個參數必須是Request對象。
接下來,我們可以直接在控制器中使用:
<?php
namespace app\index\controller;
use think\Controller;
use think\Request;
class Index extends Controller
{
public function index()
{
$info = $this->request->user($userId);
}
}
調用方法的時候不需要傳入當前請求對象,會自動傳入。