2011-05-12 44 views
2

我有一个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;  
} 

我已经使用很多,如果在这里,我认为情况不是很好,还有没有其他的办法可以判断上述条件并以更更好的方式重写代码?

回答

3

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

$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; 

本例仅使用每场一个规则,但你应该能够很容易地扩展它使用每多个规则领域。

您最初必须设置所有规则,但验证不会因为您将另一个属性添加到您的类中而增大。

+0

在我看来,这可能是更好的选择,也易于阅读。谢谢你,会玩弄它。 –

+1

@IbrahimAzharArmar看看CakePHP验证系统。这几乎是相同的原理 – JohnP

+0

@JonhP,是否有任何特定的文章与示例演示,可能对我有帮助.. –

0

,如果你想LES用的,如果条件可以使用选择的情况下与if块

线 情况1 如果块

情况下2 如果块

如果将帮助您在更好的方法

1

我不认为你可以用更好的方式重写这个特定的代码。

但是,从更大的图片看有可能的改进。看看类变量,这可能是某种形式的类或模型实例,并且您在保存数据之前试图验证数据。您可以在单独的类中概括并抽象验证逻辑。为了获得灵感,请看看各种PHP框架(例如Symphony,CakePHP)如何处理表单和模型验证。

+0

我超级不同意。他可以将它分解为每个需要检查的东西的函数。 像,我不明白你能看到“$ this-> error ['password'] ='密码长度应该在5到40个字符之间';”在代码中两次,并决定它不能大幅改进。如果他改变了密码的工作方式,他必须在这个例子中复制和粘贴两次代码。 – Anther

+1

只是将密码检查分解为单独的功能并不是我称之为实质性改进。 –

0

我不认为你可以避免这个多重If If Statements,因为我看到这个是你验证字段。

为multimple其他替代if语句是SWTICH声明

我不知道这是针对这种情况可行的,因为你逝去的字符串作为参数,其中作为开关不会采取字符串作为参数,它只需要整数作为输入

+0

switch也接受字符串作为参数。 –

0

下面是一个更加整洁的代码解决方案的样机,我没有编译它,因为..这不是我的生活的工作,但它绝对是你想要采取的路径,因为你有太多的重复自己在你的代码中。

但是,这与您现在正在做的非常接近,我只是丢失了一些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"; 
     } 
} 
1

首先,你应该提取你的错误字符串转换为定义,或更好,类常量。

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;  
} 

第二步是重构测试为单独的私有方法和摆脱如果块:

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; 
} 

在第三重构阶段,你应该提取validate_ *方法为验证器类从主类中分离验证任务。后一阶段显然取决于你(作为定义适当日志类的负担)。

相关问题