Php 有没有更好的方法来使用多个if条件?

Php 有没有更好的方法来使用多个if条件?,php,Php,我有一个php类方法,它确定类属性是否有任何值。如果它持有任何值,那么它将验证并迭代$this->error类属性。这是我正在使用的类方法 public function validate() { if(!empty($this->name)) { if(!preg_match('/^[a-zA-z ]{3,50}$/',$this->name)) { $this->error['name'] = 'Name should be

我有一个php类方法,它确定类属性是否有任何值。如果它持有任何值,那么它将验证并迭代$this->error类属性。这是我正在使用的类方法

public function validate() {
    if(!empty($this->name)) {
        if(!preg_match('/^[a-zA-z ]{3,50}$/',$this->name)) {
            $this->error['name'] = 'Name should be valid letters and should be between 3 and 25 characters';
        }
    }
    if(!empty($this->email)) {
        if(!filter_var($this->email,FILTER_VALIDATE_EMAIL)) {
            $this->error['invalidEmail'] = 'Invalid email address';
        }
        if(empty($this->userId) && $this->emailCount($this->email)) {
            $this->error['emailExist'] = 'Email already exist';
        }
    }
    if(empty($this->userId) && !empty($this->password)) {
        if(strlen($this->password) < 5 || strlen($this->password > 40)) {
            $this->error['password'] = 'Password length should be between 5 and 40 characters';
        }
    }
    if(!empty($this->userId) && !empty($this->newPassword)) {
        if(strlen($this->newPassword) < 5 || strlen($this->newPassword > 40)) {
            $this->error['password'] = 'Password length should be between 5 and 40 characters';
        }
    }
    if(!empty($this->pPhone)) {
        if(!preg_match('/^[0-9]{5,10}$/',$this->pPhone)) {
            $this->error['invalidpPhone'] = 'Invalid primary phone number';
        }
    }
    if(!empty($this->sPhone)) {
        if(!preg_match('/^[0-9]{5,10}$/',$this->sPhone)) {
            $this->error['invalidsPhone'] = 'Invalid secondary phone number';
        }
    }
    return (empty($this->error)) ? true : false;    
}
公共函数验证(){
如果(!empty($this->name)){
如果(!preg_match('/^[a-zA-z]{3,50}$/',$this->name)){
$this->error['name']='name应该是有效的字母,并且应该在3到25个字符之间';
}
}
如果(!empty($this->email)){
如果(!filter\u var($this->email,filter\u VALIDATE\u email)){
$this->error['invalidEmail']=“无效的电子邮件地址”;
}
if(空($this->userId)&&&$this->emailCount($this->email)){
$this->error['emailExist']=“电子邮件已经存在”;
}
}
if(empty($this->userId)和&!empty($this->password)){
如果(strlen($this->password)<5 | strlen($this->password>40)){
$this->error['password']=“密码长度应在5到40个字符之间”;
}
}
如果(!empty($this->userId)&&!empty($this->newPassword)){
如果(strlen($this->newPassword)<5 | strlen($this->newPassword>40)){
$this->error['password']=“密码长度应在5到40个字符之间”;
}
}
如果(!empty($this->pPhone)){
如果(!preg_match('/^[0-9]{5,10}$/',$this->pPhone)){
$this->error['invalidphone']='Invalid primary phone number';
}
}
如果(!empty($this->sPhone)){
如果(!preg_match('/^[0-9]{5,10}$/',$this->sPhone)){
$this->error['invalidsPhone']='Invalid secondary phone number';
}
}
返回(空($this->error))?真:假;
}

我在这里使用了很多我认为不是很好的if条件,是否有其他方法可以确定上述条件并以更好的方式重写代码?

如果您想使用if条件,可以使用select case with if block

线 案例1 if块

案例2 if块


if将以更好的方式帮助您

我认为您无法以更好的方式重写这段特定的代码


但是,从更大的角度来看,可能会有改进。查看类变量,这可能是一个表单类或某种类型的模型实例,您试图在保存数据之前验证数据。您可以在单独的类中概括和抽象验证逻辑。请看一看各种PHP框架(例如Symphony、CakePHP)如何处理表单和模型验证。我不认为您可以避免使用这种多If语句,因为我认为这是验证字段的地方。

多示例if语句的其他替代方法是Swtich语句


我不确定这种情况是否可行,因为您将字符串作为参数传递,因为Switch不会将字符串作为参数,它只将整数作为输入

您可以使用变量并循环代码。但这意味着您必须为代码提出某种标准化的验证方案

$validateFields = array('email', 'username', 'userId'); //list of fields to validate
$rules = array(
  'username' => array('type'=> 'regex', 'rule' => '/^[a-zA-z ]{3,50}$/'),
  'email'    => array('type' => 'filter', 'rule' => 'FILTER_VALIDATE_EMAIL')
);

foreach ($validateFields as $field) {
   if (isset($rules[$field])) {
       switch ($rules[$field]['type']) {
           case 'regex' : 
              if(!preg_match($rules[$field]['type']['rule'],$this->$field)) {
                    $this->error[$field] = ucfirst($field) . ' should be valid letters and should be between 3 and 25 characters';
              }
              break;

           case 'filter' :
              if(!filter_var($this->$field, $rules[$field]['type']['rule'])) {
                  $this->error[$field] = 'Invalid email address';
              }
              break

           //more cases
       }
   }
}
return (empty($this->error)) ? true : false; 
本例中每个字段仅使用一条规则,但您应该能够轻松地将其扩展为每个字段使用多条规则


最初必须设置所有规则,但验证不会因为向类添加另一个属性而增长

这是一个更简洁的代码解决方案的模型,我不会编译它,因为。。这不是我一生的工作,但这绝对是你想要走的道路,因为你在代码中有太多的重复

但是,是的,这与您现在正在做的非常接近,我刚刚丢失了一些ID检查和其他需要重新实现的代码

另外,我这样做的前提是这已经在一个类中,并且您正在访问类变量
$this->name

<?php 

public function validate() {
    //You can place your simple ID checks around these wherever they're supposed to go, I lost them ;P.
    //This code probably won't compile without errors, but it's to give you a much neater idea.
    //Never ever repeat code !!! Your life becomes so much better :]
    $this->validate_name($this->name);
    $this->validate_email($this->email); // I didn't complete this one.. but this is just all for an idea


    $this->validate_phone_number($this->pPhone,'Primary');
    $this->validate_phone_number($this->sPhone,'Secondary');

    return (empty($this->error)) ? true : false;    
}

function validate_password($password){
    !empty($password)) {
        if(strlen($password) < 5 || strlen($password > 40)) {
            $this->error['password'] = 'Password length should be between 5 and 40 characters';
        }
}

function validate_name($name){
        if(!preg_match('/^[a-zA-z ]{3,50}$/',$name)) {
            $this->error['name'] = 'Name should be valid letters and should be between 3 and 25 characters';
        }
}

function validate_phone_number($number,$type){
    if(!preg_match('/^[0-9]{5,10}$/',number)) {
            $this->error['invalidsPhone'] = "Invalid $type phone number";
        }
}

首先,您应该将错误字符串提取到定义中,或者更好地说,提取到类常量中

define('ERR_BAD_NAME','Name should be valid letters and should be between 3 and 25 characters');
define('ERR_BAD_EMAIL','Invalid email address');
define('ERR_EMAIL_IN_USE','Email already exist');
define('ERR_BAD_PASSWD','Password length should be between 5 and 40 characters');
define('ERR_BAD_PRIMARY_PHONE','Invalid primary phone number');
define('ERR_BAD_SECONDARY_PHONE','Invalid primary phone number');

public function validate() {
    if(!empty($this->name)) {
        if(!preg_match('/^[a-zA-z ]{3,50}$/',$this->name)) {
            $this->error['name'] = ERR_BAD_NAME;
        } 
    }
    if(!empty($this->email)) {
        if(!filter_var($this->email,FILTER_VALIDATE_EMAIL)) {
            $this->error['invalidEmail'] = ERR_BAD_EMAIL;
        }
        if(empty($this->userId) && $this->emailCount($this->email)) {
            $this->error['emailExist'] = ERR_EMAIL_IN_USE;
        }
    }
    if(empty($this->userId) && !empty($this->password)) {
        if(strlen($this->password) < 5 || strlen($this->password > 40)) {
            $this->error['password'] = ERR_BAD_PASSWD;
        }
    }

    if(!empty($this->pPhone)) {
        if(!preg_match('/^[0-9]{5,10}$/',$this->pPhone)) {
            $this->error['invalidpPhone'] = ERR_BAD_PRIMARY_PHONE;
        }
    }
    if(!empty($this->sPhone)) {
        if(!preg_match('/^[0-9]{5,10}$/',$this->sPhone)) {
            $this->error['invalidsPhone'] = ERR_BAD_PRIMARY_PHONE;
        }
    }
    return (empty($this->error)) ? true : false;    
}
define('ERR_BAD_NAME','NAME应该是有效的字母,并且应该在3到25个字符之间');
定义('ERR_BAD_EMAIL','Invalid EMAIL address');
定义('ERR_EMAIL_IN_USE','EMAIL ready exist');
定义('ERR_BAD_PASSWD','Password length应该在5到40个字符之间');
定义('ERR_BAD_PRIMARY_PHONE','Invalid PRIMARY PHONE number');
定义('ERR_BAD_SECONDARY_PHONE','Invalid primary PHONE number');
公共函数验证(){
如果(!empty($this->name)){
如果(!preg_match('/^[a-zA-z]{3,50}$/',$this->name)){
$this->error['name']=ERR\u BAD\u name;
} 
}
如果(!empty($this->email)){
如果(!filter\u var($this->email,filter\u VALIDATE\u email)){
$this->error['invalidEmail']=ERR\u BAD\u EMAIL;
}
if(空($this->userId)&&&$this->emailCount($this->email)){
$this->error['emailExist']=ERR\u EMAIL\u IN\u USE;
}
}
if(empty($this->userId)和&!empty($this->password)){
如果(strlen($this->password)<5 | strlen($this->password>40)){
$this->error['password']=ERR\u BAD\u PASSWD;
}
}
如果(!empty($this->pPhone)){
如果(!preg_match('/^[0-9]{5,10}$/',$this->pPhone)){
$this->error['invalidphone']=ERR\u BAD\u PRIMARY\u PHONE;
}
}
如果(!empty($this->sPhone)){
如果(!preg_match('/^[0-9]{5,10}$/',$this->sPhone)){
$this->error['invalidsPhone']=ERR\u BAD\u PRIMARY\u PHONE;
}
}
返回(空($this->error))?真:假;
}
第二步是将测试重构为单独的私有方法,并去掉if块:

private function validate_name($name) {
    return = empty($name) || preg_match('/^[a-zA-z ]{3,50}$/',$name);
}

private function validate_phone($phone) {
    return empty($phone) || preg_match('/^[0-9]{5,10}$/',$phone);
}

private function validate_email($email) {
   return empty($email)) || filter_var($email,FILTER_VALIDATE_EMAIL);
}

private function emailInUse($email, $userId) {
   if(!empty($email)) {
        if(empty($this->userId) && $this->emailCount($this->email)) {
            $this->error['emailExist'] = ERR_EMAIL_IN_USE;
        }
    }
}

private function validate_userPassword($userId, $password) {
    $passwordLen=strlen($this->password);
    return (empty($this->userId) && !empty($this->password)) ||
           (5 <= $passwordLen) && (40 >= $passwordLen); 
}

private function lor_error($type, $message) {
    $this->error[$type] = $message;
    return false;
}

public function validate() {
  $isValid = true;
  $isValid &= $this->validate_name($this->name) || 
              $this->logError('name',ERR_BAD_NAME);
  $isValid &= $this->validate_email($this->email) || 
              $this->logError('invalidEmail',ERR_BAD_EMAIL);
  $isValid &= $this->emailInUse($this->userId, $this->email) || 
              $this->logError('emailExist',ERR_EMAIL_IN_USE);
  $isValid &= $this->validateUserPassword($this->userId, $this->password) ||
              $this->log('password', ERR_BAD_PASSWD);
  $isValid &= $this->validate_phone($this->pPhone) ||
              $this->log('invalidpPhone',ERR_BAD_PRIMARY_PHONE);
  $isValid &= $this->validate_phone($this->sPhone) ||
              $this->log('invalidsPhone',ERR_BAD_SECONDARY_PHONE);
  return $isValid;
}
私有函数验证\u名称($name){
return=empty($name)| | preg_match('/^[a-zA-z]{3,50}$/',$name);
}
私人功能验证电话($phone){
返回空($phone)| | preg_match('/^[0-9]{5,10}$/',$phone);
}
普里瓦特