这会成为一个很好的PHP验证课程吗? [英] Would this make a good PHP validation class?

查看:50
本文介绍了这会成为一个很好的PHP验证课程吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解一下您对创建验证类的最佳方法的看法。下面我粘贴在我的版本中,它还不是很广泛,但到目前为止它是正确的方法吗?



我希望每个元素都可以出现在一个表单中应该验证具有自己的属性,字符串的字符串长度或图像或文件的文件大小(见下文)。



另外,是吗?最好将这些规则声明为嵌套数组,还是应该将它们放在一个大字符串中,然后在此过程中将其拆分?



I would like to read about your opinions on what the best way to create a validation class is. Below i pasted in my version, it's not really extensive yet, but is it the right approach so far?

I want every element which could appear in a form and which should be validated to have its own properties, in terms of string length for strings or file size for images or files in general (see below).

Also, is it better to declare these rules as nested arrays or should I put them in one big string, which would then be split up during the process?

mb_internal_encoding("UTF-8");

class Phrase {
    //creates parts of sentences, not important
    static function additive(array $limbs) {
        return implode(' and ', array_filter([implode(', ', array_slice($limbs, 0, -1)), end($limbs)], 'strlen'));
    }
}

class Text {
    static function validate($item) {
        $err = array();
        $value = $_POST[$item] ?? $_GET[$item];
        $criteria = FormProcess::$criteria[$item];
        foreach($criteria as $critKey => $critVal) {
            if($critKey === 'required' && empty($value)) {
                $err[] = "is required";
            } else if(!empty($value)) {
                switch($critKey) {
                    case 'length':
                        if(is_array($critVal)) {
                            //min and max set
                            if(mb_strlen($value) < $critVal[0] || mb_strlen($value) > $critVal[1]) {
                                $this->err[] = "must contain between {$critVal[0]} and {$critVal[1]} characters"; 
                            }
                        } else {
                            //max set only
                            if(mb_strlen($value) > $critVal) {
                                $err[] = "must contain a maximum of $critVal characters";
                            }
                        }
                    break;
                    case 'pattern':
                        if(!preg_match($critVal[0], $value)) {
                            $err[] = "may consist of {$critVal[1]} only";
                        }
                    break;
                    case 'function':
                        $result = static::$critVal($value);
                        if($result) {
                            $err[] = $result;
                        }
                    break;
                }
            }
        }
        if(!empty($err)) {
            return "{$criteria['name']} " . Phrase::additive($err) . "!";
        }
        return false;
    }

    private static function email($email) {
        //checks if given string is a valid email address
        if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            return "is invalid";
        }
        return false;
    }
}

class File {
    //checks for aspects like filesize...
    static function validate() {
        //...
    }   
}

class Image extends File {
    static function validate() {
        parent::validate(); //perform general file checks first
        //...checks for images specifically
    }
}

class Video extends File {
    static function validate() {
        parent::validate(); //perform general file checks first
        //...checks for videos specifically
    }
}

class FormProcess {
    public $errors;

    //declare, what kind of requirements the items must meet
    static $criteria = array(
        'email' => array(
            'type'     => 'Text',
            'required' => true,
            'name'     => 'Email',
            'length'   => 48,
            'function' => 'email', 
        ),

        'username' => array(
            'type'     => 'Text',
            'required' => true,
            'name'     => 'Username',
            'length'   => [4, 24],
            'pattern'  => ['/^[-\w]+$/', "alphanumeric characters, underscores and hyphens"],
        ),

        'password' => array(
            'type'     => 'Text',
            'required' => true,
            'name'     => 'Password',
            'length'   => [6, 100],
            'pattern'  => ['/^[\S]+$/', "non-whitespace characters"],
        ),
    );

    //runs the validate function on each item while storing occuring errors
    function __construct(array $items) {
        foreach($items as $item) {
            $class = self::$criteria[$item]['type'];
            $result = $class::validate($item);
            if($result) {
                $this->errors[] = $result;
            }
        }
    }
}



然后你所要做的就是命名所有预期的项目(通过它们在数组中的html'name'属性)并将其传递给构造函数,然后构造函数会在每个项目上运行相应的验证函数。


Then all you had to do, is, naming all expected items (by their html 'name' attribute in the form) in an array and pass it through the constructor, which would then run the appropriate validation function on each item.

$expected = ['username', 'password'];
$signup = new FormProcess($expected);

if($signup->errors) { 
    echo "There was something wrong with your request:<ul>";
        foreach($signup->errors as $error) {
            echo "<li>$error</li>";
        }
    echo "</ul>";
}



我希望从错误中吸取教训并在需要的地方对代码进行改进。提前谢谢!



我尝试了什么:



我在GitHub上查找各种存储库并分析方法,Zend用于验证系统的框架。


I hope to learn from mistakes and make improvements to the code from you where they are needed. Thank you in advance!

What I have tried:

I looked up various repositories on GitHub and analyzed the methods, which frameworks like Zend were using for validation systems.

推荐答案

肢体){
return implode(' 和',array_filter([implode(< span class =code-string>' ,',array_slice(
limbs) { return implode(' and ', array_filter([implode(', ', array_slice(


limbs,0,-1 )),结束(
limbs, 0, -1)), end(


肢体)],' strlen'));
}
}

class 文字{
静态函数验证(
limbs)], 'strlen')); } } class Text { static function validate(


这篇关于这会成为一个很好的PHP验证课程吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆