更有效的方式,而不是使用重复的if语句

时间:2014-06-01 23:25:43

标签: php

我有这段代码:

if (strtolower($_POST['skype']) == "yummy") 
   echo "<pre>".file_get_contents("./.htfullapps.txt")."</pre>";
elseif ($_POST['skype'] == '' or 
        $_POST['IGN'] == '' or 
        $_POST['pass'] == '' or 
        !isset($_POST['rules']) or 
        !isset($_POST['group']) or 
        strlen($_POST['pass']) <= 7)
{
    redir( "http://ftb.chipperyman.com/apply/?fail&error=one%20or%20more%20fields%20did%20not%20meet%20the%20minimum%20requirements" ); //Redir is a function defined above and works fine.
    exit;
}

但是,我想开始报告具体的错误。例如,这就是我用if语句做的方式:

...
elseif ($_POST['skype'] == '') redir( "http://ftb.chipperyman.com/apply/?fail&error=your%20skype%20is%20invalid%20because%20it%20is%20empty" ); 
elseif ($_POST['IGN'] == '') redir( "http://ftb.chipperyman.com/apply/?fail&error=your%20IGN%20is%20invalid%20because%20it%20is%20empty" ); 
elseif ($_POST['pass'] == '') redir( "http://ftb.chipperyman.com/apply/?fail&error=your%20password%20is%20invalid%20because%20it%20is%20empty" ); 
elseif (strlen($_POST['pass']) <= 7) redir( "http://ftb.chipperyman.com/apply/?fail&error=your%20password%20is%20invalid%20because%20it%20does%20not%20meet%20minimum%20length%20requirements" ); 
...

然而,这很大,很乱,而且效率低下。这会有什么解决方案?

5 个答案:

答案 0 :(得分:3)

您可以像这样使用关联数组。

function redir($var){
    echo $var;
}

$skypeErr = array(''=>"http://ftb.chipperyman.com/apply/?fail&error=your%20skype%20is%20invalid%20because%20it%20is%20empty");
$IGNErr = array(''=>'err2');
$passErr = array(''=>'err3',True:'err4');

redir($skypeErr[$_POST['skype']]);
redir($IGNErr[$_POST['IGN']]);
redir($passErr[$_POST['pass']]);
redir($passErr[strlen($_POST['pass'])<=7]);

答案 1 :(得分:2)

创建用于解析post和get数据的Request类,该类可以帮助您验证未定义的空字段和Report类,它可以帮助您抛出错误。

这是非常简单的Request类:

class Request {
    protected $items = array(
                             'get' => array(),
                             'post' => array()
                       );
    public function __construct(){
        $this->items['post'] = $_POST;
        $this->items['get'] = $_GET;
    }

    public function isPost(){
        return ($_SERVER['REQUEST_METHOD'] == 'POST') ? true : false;
    }

    public function isGet(){
       return ($_SERVER['REQUEST_METHOD'] == 'GET') ? true : false;
    }

    public function getPost($name){
        return (isset($this->items['post'][$name])) ? $this->items['post'][$name] : null; 
    }

    public function get($name){
       return (isset($this->items['get'][$name])) ? $this->items['get'][$name] : null;
    }
}

报告类:

Class Report {
    protected static $instance;
    private $messages = array();

    private function __construct(){}

    public function getInstance(){
        if(!self::$instance){
            self::$instance = new self();
        }

        return self::$instance;
    }

    public function addReport($message){
        $this->messages[] = $message;
    }

    public function hasReports(){
        return (!empty($this->messages)) ? true : false;
    }
    public function getReports(){
       return $this->messages;
    }

    //this is not so cleaned .... it must be in template but for example
    public function throwReports(){
        if(!empty($this->messages)){
           foreach($this->messages as $message){
               echo $message."<br />";
           }
        }
    }
}

因此,如何使用是针对您的问题:

$request = new Request();
$report = Report::getInstance();
if($request->isPost())
{
  if(!$request->getPost("icq")){
    $report->addMessage("you dont enter ICQ");
  }

  if(!$request->getPost("skype")){
    $report->addMessage("you dont enter SKYPE");
  }
  //....etc

  //if we have some reports throw it.
  if($report->hasReports()){
      $reports->throwReports();
  }
}

报告类可以与会话结合并在重定向后抛出错误,只需更新类以将报告保存到会话而不是$ messages,并且在重定向之后如果你将有消息抛出它并同时清除。< / p>

答案 2 :(得分:1)

怎么样

$field_min_len = array('skype' => 1, 'IGN' => 1, 'pass' => 7);
for ($field_min_len as $f => $l) {
  if (!isset($_POST[$f]) || strlen($_POST[$f]) < $l) {
    redir(...);
    exit;
  }
}

答案 3 :(得分:0)

也许是类似的东西(可重复使用,但很冗长):

// validation parameters
$validation = array(
   'skype' => array('check' => 'not_empty', 'error' => 'skype empty'),
   'IGN'   => array('check' => 'not_empty', 'error' => 'IGN empty'),
   'pass'  => array('check' => 'size', 'params' => array(7), 'error' => 'invalid password'),
   'group' => array('check' => 'set', 'error' => 'group unset'),
   'rules' => array('check' => 'set', 'error' => 'group unset')
);

// validation class
class Validator {

  private $params;
  private $check_methods = array('not_empty', 'size', 'set');

  public function __construct($params){
    $this->params = $params;
  }

  private function not_empty($array, $key){
    return $array[$key] == '';
  }

  private function size($array, $key ,$s){
    return strlen($array[$key]) < $s;
  }

  private function set($array, $key){
    return isset($array[$key]);
  }

  private handle_error($err, $msg){
    if ($err) {
       // log, redirect etc.
    }
  }

  public function validate($data){

    foreach($params as $key => $value){
      if (in_array($value['check'], $this->check_methods)){
        $params = $value['params'];
        array_unshift($params, $data, $key);
        $this->handler_error(call_user_func_array(array($this,$value['check']),
                                                  $params),
                             $value['error']);
      }
    }
  }
};


// usage
$validator = new Validator($validation);
$validator->validate($_POST);

只需使用新的检查,特殊日志功能等扩展课程。

警告:未经测试的代码。

答案 4 :(得分:0)

这就是我现在的错误报告方式:

$errors = array('IGN' => 'You are missing your IGN', 'skype' => 'You are missing your skype'); //Etc
foreach ($_POST as $currrent) {
    if ($current == '' || $current == null) { 
        //The error should be stored in a session, but the question asked for URL storage
        redir('/apply/?fail='.urlencode($errors[$current])); 
    }
}