我有一些问题,也会对我为这个函数编写代码的方式得到一些反馈;它验证给定的电子邮件是否已存在于数据库中并返回布尔值。
/**
* Validate user existence by email
*
* @param string $email
*
* @return boolean
*/
public static function validateUserByEmail($email)
{
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
throw new InvalidFormatException('An invalid email has been provided!', 100);
}
try {
$connection = new Database();
} catch(DatabasePDOException $e) {
throw $e;
}
if($connection){
$sql = 'SELECT count(1) AS existence
FROM userprofile WHERE ename = ?';
$params = array($email);
$response = $connection->selectPDOStatement($sql, $params);
}
if(isset($response)){
return !!$response ? !!$response[0]['existence'] : false;
} else {
return false;
}
}
我的疑虑/问题如下:
1)如果电子邮件格式无效,我是否应该抛出异常
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
throw new InvalidFormatException('An invalid email has been provided!', 100);
}
或者我应该只返回一个值?
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
return false;
}
2)如果我抛出一个异常,但我没有在父函数中捕获它们,我是否做错了?
public function parentFunction($string){
if(validateUserByEmail($string)){
// do something
}
}
3)或者是完全没必要编写函数的方式?
答案 0 :(得分:1)
try/catch
阻止,更高级别可以获取详细信息。例如。 public static function validateUserByEmail($email, &$error_reason)
{
$result = true;
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$result = false;
$error_reason = 'InvalidEmail';
}
...
return $result;
}