在中間件中,注入app\common\service\AuthService 類
用DI
#[Inject]
private AuthService $authService;
注入,報錯
Typed property app\\common\\middleware\\Auth::$authService must not be accessed before initialization
變成只能new一個
public function __construct($data)
{
$this->data = $data;
$this->authService = new AuthService();
}
好像Typed property app\common\service\AuthService::$authDao must not be accessed before initialization
通過中間件調(diào)用 AuthService 類, AuthService 類中通過
#[Inject]
private AuthDao $authDao;
調(diào)用AuthDao,也是失敗的,而控制器中調(diào)用AuthService是正常的,也就是說通過中間件的所有業(yè)務(wù)流程中都不能使用DI,
有辦法解決嗎
調(diào)用的看到了
改為Container調(diào)用正常,但中間件中使用
#[Inject]
private AuthService $authService;
依然不行
之前有定位到的,考慮到是否實例化的時候也是通過new的而沒有通過container,但發(fā)現(xiàn)代碼是正確的
foreach ($middlewares as $key => $item) {
$middleware = $item[0];
if (is_string($middleware)) {
$middleware = static::container($plugin)->get($middleware);
} elseif ($middleware instanceof Closure) {
$middleware = call_user_func($middleware, static::container($plugin));
}
if (!$middleware instanceof MiddlewareInterface) {
throw new InvalidArgumentException('Not support middleware type');
}
$middlewares[$key][0] = $middleware;
}
所以暫時沒有實際導(dǎo)致不能使用的原因