简体   繁体   中英

server side user input validation - class design*

I test user input both the client and server side. On the server side there is a short simple class composed of static functions which validate user input. Class sign-up and sign-in call these functions. My concern is that I should not be using static functions. Should I be using static functions to validate user input? Thanks.

/*check*/

class check 
{
    static function empty_user($a)
    {
        return (int)!in_array('',$a); 
    }   

    static function name($a)
    {
        return preg_match('/^[a-zA-Z-\.\s]{1,40}$/',$a);
    }

    static function email($a)
    {
        return preg_match('/^[a-zA-Z0-9._s-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{1,4}$/',$a);
    }

    static function pass($a)
    {
        return preg_match('/^[a-zA-Z0-9!@#$%^&*]{6,20}$/',$a);
    }
}

The purpose of the class is ultimately not relevant for the decision about static vs. non-static member functions. What matters if objects of the class has a state , or if the class is merely a stand-in for a namespace.

In the latter case, the class just collects a bunch of loosely related function in a common namespace, but you would never instantiate the class. In the former case, you should put all the data that's common to the design purpose of the class into the class as private members and use those members in your (non-static) functions.

In your example, I could see that you make $a a private member:

class CheckInput
{
    private $data;

    public function init($a) { $this->data = $a; } // or write a constructor

    public function email() { ... $this->data ... }

    // ...
}

That way, you instantiate one CheckInput object for each set of input data.

我对此的看法是,如果这只是一个Utility类,那么静态函数应该完成这项工作。

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