有人有一個很好的做法來在插入數據庫之前處理數據驗證,而無需將所有內容都包裝到 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 = '[email protected]'; 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 關注
- 172 瀏覽
添加回答
舉報
0/150
提交
取消