为什么在FormRequest子类中的构造函数调用Request类中的方法不可以,但其它方法中调用就行
这个说起来拗口,给个示例吧
class AccountRequest extends FormRequest
{
private $account;
public function __construct(Request $request) {
$this->route(); // 这里这样调用就不行,很奇怪,FormRequest不也是继承自Request类吗?
$this->account = $request->route()->account; // 想在构造函数中使用,试来试去,只有依赖注入
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\Rule|array|string>
*/
public function rules(): array
{
$this->route(); // 这样调用是可以,因为我除了在rules中使用外,还会在withValidator等方法中使用,所以放在构造函数合理
formrequest 是继承 Request 类,route()方法可以调用,但是否返回 Null,这是因为 $request 的属性转移到 formrequest 身上是在 app容器 resolving 阶段,也就是 container 的 resolve() 中调用fireResolvingCallbacks方法,而之前 formrequest 已经被实例化,所以在此之前还只是个空壳