Table of Contents
Problems encountered when password encryption
Take it out separately and test it
tested the modifiers alone
Test data completion
Find the reason
Solving the initial problem
When only the data is completed but no value is assigned
Summary
Home PHP Framework ThinkPHP Introducing the relationship between thinkphp5.0 modifier and data completion and how to use it

Introducing the relationship between thinkphp5.0 modifier and data completion and how to use it

Apr 27, 2021 pm 04:39 PM
php

The following tutorial column of thinkphp will introduce to you the relationship between thinkphp5.0 modifier and data completion and how to use it. I hope it will be helpful to friends in need!

The relationship between thinkphp5.0 modifier and data completion and how to use it

Problems encountered when password encryption

Today I encountered the problem of password md5 encryption, At that time, "thinkphp5.0.9->Model->Data Completion" was used to implement automatic encryption, but in the "thinkphp5.0.9->Model->Modifier" above, it was found that the modifier has the same function as the data completion , read the comments below that it is used in conjunction with data completion and modifiers, so I followed it and wrote like this:
//模型层

class User extends Model{
//$auto包含新增$insert和更新操作$update,就是不管新增还是更新我就自动执行
    protected $auto = ['password','create'];
    public function setPasswordAttr($value)
    {
        return md5($value);
    }
    public function setCreateAttr()
    {
        return time();
    }
    
//注册用户
    public function register($data){
            $bool = $this->save($data);
            return $bool ? $this->id : 0;
    } 
}

//控制器层方法
public function register()
    {
        if(request()->isAjax()){
            $userModel=new \app\index\Model\User();
            $data=input('post.');
//注册
            $res = $userModel->register($data);
           echo $res;
        }else{
            $this->error('非法访问');
        }
    }
Copy after login

Introducing the relationship between thinkphp5.0 modifier and data completion and how to use it

I entered "wwwwww" according to the above After the code is registered, the password encryption result is b8d3c8f4db0c248ac242dd6e098bbf85

The correct encryption result is d785c99d298a4e9e6e13fe99e602ef42. You may not notice it at this time. When you log in, you cannot log in. You must register a new user. For example, the password is still wwwwww. When you log in, you still can't log in. You can only suspect that there is an encryption error. Then you find "setPasswordAttr() with data completed"

Take it out separately and test it

Just tell me the answer Well, I looked at the modifiers and data multiple times and completed the test for two hours and finally found out the reason. The newly created test table

Introducing the relationship between thinkphp5.0 modifier and data completion and how to use it

//新建test模型层
namespace app\index\Model;
use think\Model;
class Test extends Model
{
    protected $auto = ['password'];
    protected function setPasswordAttr($value)
    {
        dump(md5(NULL));
        dump($value);
        dump(md5($value));
        return md5($value);

    }
    public function addPass(){
        echo "修改器";
        $this->password='wwwwww';
        dump($this->password);
        
        echo "数据完成";
        $this->save([
            'username'  => 'thinkphp',
            'password'  => 'wwwwww',
            'create'    => '123456'
        ]);
    }
}

//控制器中添加test方法
 public function test(){
        $user = model('Test');
        //调用model层函数
        $user->addPass();
    }
Copy after login

tested the modifiers alone

First comment out the "data completion" part in the model layer
namespace app\index\Model;
use think\Model;
class Test extends Model
{
    protected $auto = ['password'];
    protected function setPasswordAttr($value)
    {
        dump(md5(NULL));//把NULL加密
        dump($value);   //查看调用时传递过来的值
        dump(md5($value));//把该值加密
        return md5($value);//把该值加密返回

    }
    public function addPass(){
        echo "修改器:修改器的作用是可以在数据赋值的时候自动进行转换处理";
        $this->password='wwwwww';
        dump($this->password);//输出返回后的结果

//        echo "数据完成:在数据字段insert,update,auto时进行处理";
//        $this->save([
//            'username'  => 'thinkphp',
//            'password'  => 'wwwwww',
//            'create'    => '123456'
//        ]);
    }
}
Copy after login
After execution, the page displays the results. Through the results, it is found that the modifier is automatically encrypted when assigning values. Note: it is not stored at this time. database!
修改器:修改器的作用是可以在数据赋值的时候自动进行转换处理

string(32) "d41d8cd98f00b204e9800998ecf8427e"【加密的NULL】

string(6) "wwwwww"【传过来的$value】

string(32) "d785c99d298a4e9e6e13fe99e602ef42"【加密$value】

string(32) "d785c99d298a4e9e6e13fe99e602ef42"【return返回的结果】
Copy after login

Test data completion

Comment out the code in the "modifier" part and only execute the data completion
namespace app\index\Model;
use think\Model;
class Test extends Model
{
    protected $auto = ['password'];
    protected function setPasswordAttr($value)
    {
        dump(md5(NULL));//把NULL加密
        dump($value);   //查看调用时传递过来的值
        dump(md5($value));//把该值加密
        return md5($value);//把该值加密返回

    }
    public function addPass(){
//        echo "修改器:修改器的作用是可以在数据赋值的时候自动进行转换处理";
//        $this->password='wwwwww';
//        dump($this->password);//输出返回后的结果

        echo "数据完成:在数据字段insert,update,auto时进行处理";
        $this->save([
            'username'  => 'thinkphp',
            'password'  => 'wwwwww',
            'create'    => '123456'
        ]);
    }
}
Copy after login

Find the reason

After executing setPasswordAttr( ) is executed twice, so the password is also encrypted twice;
数据完成:在数据字段insert,update,auto时进行处理

string(32) "d41d8cd98f00b204e9800998ecf8427e"【加密NULL】

string(6) "wwwwww"【传入的$value】

string(32) "d785c99d298a4e9e6e13fe99e602ef42"【加密$value="wwwwww"】

string(32) "d41d8cd98f00b204e9800998ecf8427e"【加密NULL】

string(32) "d785c99d298a4e9e6e13fe99e602ef42"【传入的$value】

string(32) "b8d3c8f4db0c248ac242dd6e098bbf85"【再次加密$value="d785c99...f42"】
Copy after login
The reason why it is encrypted twice is that it is encrypted once when assigning a value and once when $auto is automatically completed
[
    'username'  => 'thinkphp',
    'password'  => 'wwwwww',
    'create'    => '123456'
]
Copy after login

Solving the initial problem

If you want to encrypt once, comment out protected $auto = ['password'];, or perform md5(md5("wwwwww")) in the login code and comment out After execution:
数据完成:在数据字段insert,update,auto时进行处理

string(32) "d41d8cd98f00b204e9800998ecf8427e"【加密NULL】

string(6) "wwwwww"【$value】

string(32) "d785c99d298a4e9e6e13fe99e602ef42"【加密结果】
Copy after login

Introducing the relationship between thinkphp5.0 modifier and data completion and how to use it

If there are multiple fields protected $auto = ['password','create']; just remove the password protected $auto = [ 'create'];, so the original problem is solved.

When only the data is completed but no value is assigned

You may have noticed above how I always encrypt NULL. There is another situation where protected $auto = ['password']; definition Automatically completed, but I did not assign a value:
namespace app\index\Model;
use think\Model;
class Test extends Model
{
    protected $auto = ['password'];
    protected function setPasswordAttr($value)
    {
        dump(md5(NULL));//把NULL加密
        dump($value);   //查看调用时传递过来的值
        dump(md5($value));//把该值加密
        return md5($value);//把该值加密返回

    }
    public function addPass(){
//        echo "修改器:修改器的作用是可以在数据赋值的时候自动进行转换处理";
//        $this->password='wwwwww';
//        dump($this->password);//输出返回后的结果

        echo "数据完成:在数据字段insert,update,auto时进行处理";
        $this->save([
            'username'  => 'thinkphp',
//注释掉,不赋值
 //           'password'  => 'wwwwww',
            'create'    => '123456'
        ]);
    }
}
Copy after login
After execution, the encryption is NULL
数据完成:在数据字段insert,update,auto时进行处理

string(32) "d41d8cd98f00b204e9800998ecf8427e"【加密NULL】

NULL【没有传值,$value=NULL】

string(32) "d41d8cd98f00b204e9800998ecf8427e"【加密$value,刚好等于NULL加密结果】
Copy after login

Introducing the relationship between thinkphp5.0 modifier and data completion and how to use it

The remaining $update and $insert usage methods Like $auto, $auto includes $update and $insert

Summary

The modifier will be executed when assigning; data completion will be executed twice, once when assigning and once when writing When entering data
I hope the manual can be a little more detailed, as it wastes my development time. I would like to share this with you so that everyone can avoid pitfalls. Please correct me if you understand something wrong, thank you

The above is the detailed content of Introducing the relationship between thinkphp5.0 modifier and data completion and how to use it. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

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

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

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,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

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

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

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

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

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.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

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.

See all articles