validate()) { $errors = $this->getFirstErrors(); $message = reset($errors); util::fail($message); return false; } return true; } /** * 自动加载并验证请求数据 * * 自动检测请求类型(GET 或 POST),加载对应的数据并进行验证。 * 相比手动指定 $method 参数,使用 $request->isGet 和 $request->isPost * 是 Yii 框架推荐的做法,更符合框架风格。 * * 使用示例: * - POST 请求自动加载:$form->loadAndValidate(); * - GET 请求自动加载:$form->loadAndValidate(); * * @param string $formName 表单名称,用于嵌套数据 * @return bool 验证成功返回 true,失败自动输出错误响应 * @throws \yii\base\InvalidConfigException */ public function loadAndValidate($formName = '') { $request = Yii::$app->request; // ✨ 优化:使用 Yii 提供的方法检查请求类型 // 相比手动字符串比较 ($method === 'get'),这种方式更符合框架风格 if ($request->isGet) { $data = $request->get(); } elseif ($request->isPost) { $data = $request->post(); } else { util::fail('不支持的请求方法'); return false; } if (!$this->load($data, '')) { util::fail('数据加载失败'); return false; } return $this->validateForm(); } }