Specific use of ThinkPHP5 validator
This article mainly introduces the specific use of ThinkPHP5 validator, which has certain reference value. Now I share it with everyone. Friends in need can refer to it
Foreword:
When we are doing API development, we will accept parameters from the client. Everyone knows that this parameter is not trustworthy. Our back-end developers must verify this parameter. . I only knew about the tp5 validator in previous development, but I didn't know its purpose, because the previous development verification was often based on model fields. The validator is more suitable for API development. Today I will briefly talk about the use of the validator
Directory:
-
Create a validator
Write a separate validator
Call verification
1. Create a validator
First we need a folder to store our validator. We create a folder at the same level as the controller under the module and name it validate
Then we can create the validator. We only need to create a class and inherit the validate class of tp5.
But friends who are familiar with object-oriented thinking must know that when we need a method that must be used by every validator, but do not modify the source code of tp5. We will write one more class as our base class. All validators inherit this base class, and then this base class inherits the validate class of tp5.
Here we name it baseValidate
Now let’s create a serious validator. For example:
1 2 3 4 5 6 7 8 9 10 11 12 |
|
Then instantiate it in the controller or model and then call
1 2 3 4 5 6 7 8 9 10 11 |
|
The application of such a validator is now written. Let's see if there's anything we can simplify.
First of all, the data that needs to be verified is what we receive from the client. Then, the first step is to accept the data
Then we have to The data is verified. If the verification fails, the error message
is returned. These two steps are performed every time the interface is requested. Then we want to encapsulate this into BaseValidate
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
|
After the goCheck method is encapsulated, someone may ask, where is the verification rule? Woolen cloth?
2. Write a separate validator
#I have said before that BaseValidate is used to be inherited, so for the real validator, we also Didn't start writing. The rules are formulated into this validator. For a deeper understanding, here is an example using custom validation rules. In fact, the verification rules written by tp should be sufficient.
Let’s take the most commonly accepted data as an example, which is id. Normally, this id represents the id of a certain piece of data in our database. We often design this id as an unsigned auto-incrementing primary key, which is translated into human language as a positive integer. Then if the parameter passed by the customer is a negative number or a decimal, it should not pass the verification.
We create a validator based on the above requirements. The location is still the same as before in the validate folder
and is named IdMustBePositiveInt.php (the name is a bit long, but fortunately the text is clear)
First of all, we must inherit our basic validator
1 |
|
and then formulate rules to assign a value to a fixed member variable
1 2 3 4 |
|
So how to do custom rules? It’s actually simple. Define a protected method
1 2 3 4 5 6 7 8 9 |
|
! ! Note: If the judgment fails here: the return is not false but an error message.
3. Call verification
According to our previous encapsulation, the effect we need to achieve is to accept parameters and verify the parameters as one. So now how do we call verification?
Here comes the awesome one, let’s take ID as an example
1 2 3 4 5 |
|
- ##Just this one line of code can directly complete the verification. When we instantiate the id validator, we call the goCheck method of its parent class.
- The goCheck method will accept parameters and pass the parameters into the check method on the validate object
- will match what we have in the id validator The require rules specified in $rule and our custom rules.
- If all pass, it will return true
- If one of them does not match, an exception will be thrown
这次只举了id为例子,虽然看上去比直接写独立验证麻烦很多,但是大家仔细想想,这个验证规则其实在很多地方都是一样的,比如密码验证规则,用户名验证规则等,当这个项目写完了。你已经完成了很多验证器。其实在下个项目中还可以继续套用的哦
TP5验证规则使用
①静态调用(使用内置的规则验证单个数据,返回值为布尔值)
1 2 3 4 5 6 7 8 9 10 11 12 |
|
②模型验证(在模型中的验证方式)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
③控制器验证(控制器中进行验证)
如果你需要在控制器中进行验证,并且继承了\think\Controller的话,可以调用控制器类提供的validate方法进行验证,如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
控制器中的验证代码可以简化为:
1 2 3 4 5 |
|
如果要使用场景,可以使用:
1 2 3 4 5 |
|
在validate方法中还支持做一些前置的操作回调,使用方式如下:
1 2 3 4 5 |
|
好了,本次tp5验证器的介绍了就写到这里了,希望对大家的学习有所帮助。
相关推荐:
The above is the detailed content of Specific use of ThinkPHP5 validator. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7
