有人有一个很好的做法来在插入数据库之前处理数据验证,而无需将所有内容都包装到 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 {}
繁花不似锦