简体   繁体   English

服务器端用户输入验证 - 类设计*

[英]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: 在您的示例中,我可以看到您将$a a设为私有成员:

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. 这样,您为每组输入数据实例化一个CheckInput对象。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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