有人有一个很好的做法来在插入数据库之前处理数据验证,而无需将所有内容都包装到 try/catch 中吗?try{ (new DB_table)->put();}catch(User_error $e){ echo "Error: Something could not be validated!";}class DB_table extends DB { public $name = 'john doe'; public $address = 'tall cedar road 123'; public $email = 'john@doe.com'; public function put(){ $this->validate_name('name'); $this->validate_address('address'); $this->validate_email('email'); if($this->errors){ throw new User_error(); } // insert data into database }}class DB { protected $errors = []; protected function validate_name(string $key){ try{ $this->$key = trim($this->$key); // some validation throw new Input_error('Name could not be validated'); } catch(Input_error $e){ $this->errors[$key] = $e->getMessage(); } } protected function validate_address(string $key){ try{ $this->$key = trim($this->$key); // some validation throw new Input_error('Address could not be validated'); } catch(Input_error $e){ $this->errors[$key] = $e->getMessage(); } } protected function validate_email(string $key){ try{ $this->$key = trim($this->$key); // some validation throw new Input_error('E-mail could not be validated'); } catch(Input_error $e){ $this->errors[$key] = $e->getMessage(); } }}class Input_error extends Error {}class User_error extends Error {}
1 回答
繁花不似锦
TA贡献1851条经验 获得超4个赞
我会将您的验证逻辑与您的DB_table课程分开。
您可以创建一个验证器类,如果验证了内容,则返回 true/false。
如果你使用一个框架,他们可能已经有了这样的东西。否则你可以实现自己的并从Laravel 的验证器中获得灵感
它是这样使用的:
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
if ($validator->fails()) {
return redirect('post/create')
->withErrors($validator)
->withInput();
}
//if you reached this line, then feel free to insert into DB
- 1 回答
- 0 关注
- 151 浏览
添加回答
举报
0/150
提交
取消