简体   繁体   中英

How can I simplify the checking/validating logic in PHP?

Here is a sample code of how to write something based on email, session key, and message. I use most of the code in error handling, like this:

First, I need check null, then, the length, session, connection with db, lastly, the actually result.... ....It is very ignoring, and the code become very long, how can I simify this? Thank you.

if(checkNullExisit($aEmail, $aSessionKey, $aMessage)){    
    //Null params detect
    return;
}  

if(strlen($aEmail) > MAX_EMAIL || strlen($aSessionKey) > MAX_SESSIONKEY ||  strlen($aMessage) > MAX_MESSAGE){
    //Too long
    return;
}      

 if(isSessionValid($aEmail, $aSessionKey)){                   
    if(connectDatabase()){ 

        if(DBManagerSingleton::saveMessage($aEmail, $aSessionKey, $aMessage, NULL)){
            //The ONLY Success Case
            return;
        }else{
            //Can't write in DB
            return;
        }

    }else{
       //DB Cannot Connect   
       return;
    }

 }else{
      //Invalid Session     
      return;
 }

If you want to shorten your validation and db connections, I think you have two main ways of going about that.

  • Procedural: Write functions for this stuff. Eg you could just have a valid_email() function.
  • OOP: Use OOP to create classes you need, eg form validation class

I feel your pain , validation is a PITA , using a framework or stand-alone libraries like Respect or Phorms might ease out your pain...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM