如何通过isset检查与错误设置优化PHP的checkDataCorrectness方法?
代码优化方案
先修正Model基类的语法错误
原isCorrect方法存在函数调用语法错误和拼写问题,先修复:
- 函数调用需加括号:
is_uploaded_file、getimagesize是函数,需传入参数并使用括号调用 - 拼写错误:
$lenght改为$length - 新增空值判断:避免
$data为null时触发strlen报错
修正后的Model代码:
namespace application\core; use application\lib\Db; use application\lib\Auth; abstract class Model { public array $route; public string $error; /* 其他方法 */ public function isCorrect(string $data = null, int $lengthFrom = null, int $lengthTo = null, $regex = null, $image = null, ) { if (isset($image)) { return is_uploaded_file($image['tmp_name']) && getimagesize($image['tmp_name']) !== false; } if ($data === null) { return false; } $length = strlen($data); $correctStartLength = $lengthFrom === null ? true : $length >= $lengthFrom; $correctEndLength = $lengthTo === null ? true : $length <= $lengthTo; $correctReg = $regex === null ? true : preg_match($regex, $data); return $correctStartLength && $correctEndLength && $correctReg; } }
优化Account类
核心优化思路
将校验规则、表单字段、错误信息整合为统一的配置数组,通过循环遍历完成所有校验,彻底消除重复的if判断,大幅简化checkDataCorrectness方法,同时让规则维护更直观。
优化后的Account代码:
namespace application\models; use application\core\Model; class Account extends Model { // 统一配置校验规则:键为表单字段名,值包含校验参数与错误提示 private array $validationRules = [ 'name' => [ 'source' => 'post', 'lengthTo' => 30, 'error' => 'Ошибка. Имя должно быть до 30 символов' ], 'last_name' => [ 'source' => 'post', 'lengthTo' => 30, 'error' => 'Ошибка. Фамилия должна быть до 30 символов' ], 'address' => [ 'source' => 'post', 'lengthTo' => 100, 'error' => 'Ошибка. Адрес должен быть до 100 символов' ], 'vk_url' => [ 'source' => 'post', 'regex' => "#(https://)?(vk.com/)([a-zA-Z0-9]+)#mi", 'error' => 'Ошибка. Неверный формат ссылки VK' ], 'steam_url' => [ 'source' => 'post', 'regex' => "#(?<CUSTOMPROFILE>https?\://steamcommunity.com/id/[A-Za-z_0-9]+)|(?<CUSTOMURL>/id/[A-Za-z_0-9]+)|(?<PROFILE>https?\://steamcommunity.com/profiles/[0-9]+)|(?<STEAMID2>STEAM_[10]:[10]:[0-9]+)|(?<STEAMID3>\[U:[10]:[0-9]+\])|(?<STEAMID64>[^/][0-9]{8,})#", 'error' => 'Ошибка. Неверный формат ссылки Steam' ], 'biography' => [ 'source' => 'post', 'lengthTo' => 600, 'error' => 'Ошибка. Биография должна содержать до 600 символов' ], 'image' => [ 'source' => 'file', 'error' => 'Файл не является изображением' ] ]; /* 其他方法 */ public function checkDataCorrectness() { foreach ($this->validationRules as $field => $rule) { // 从对应来源获取字段值 $value = match($rule['source']) { 'post' => $_POST[$field] ?? null, 'file' => $_FILES[$field] ?? null, default => null }; if ($value === null) { continue; // 字段未提交则跳过校验 } // 调用isCorrect执行校验 $isValid = match($rule['source']) { 'post' => $this->isCorrect( $value, lengthTo: $rule['lengthTo'] ?? null, regex: $rule['regex'] ?? null ), 'file' => $this->isCorrect(image: $value), default => true }; if (!$isValid) { $this->error = $rule['error']; return false; } } return true; } }
优化效果说明
- 代码大幅精简:将原7个重复的
if判断压缩为循环逻辑,新增校验字段只需在配置数组中添加条目,无需修改校验逻辑 - 维护成本降低:校验规则、错误信息与字段绑定,修改规则时无需跨区域查找
- 鲁棒性提升:通过
?? null处理字段未提交的情况,避免Undefined index报错 - 可读性增强:配置数组清晰展示所有校验要求,逻辑流程一目了然
内容的提问来源于stack exchange,提问作者MTZoom
相关产品推荐
相关产品推荐

