Home > PHP Framework > ThinkPHP > body text

ThinkPHP: The second of three powerful tools for models (modifier)

爱喝马黛茶的安东尼
Release: 2019-12-16 17:01:07
forward
2666 people have browsed it

ThinkPHP: The second of three powerful tools for models (modifier)

Modifier is one of the three major "tools" of the model. In this article, we will summarize the usage of the modifier and some precautions.

Define the modifier

The function of the modifier is to perform some necessary data processing before the model object data is written to the database. The standard definition of the modifier is as follows:

public function setFieldNameAttr($value, $data)
{
    // 对value值进行处理 data参数是当前全部数据
    // 返回值就是实际要写入数据库的值
    return $value;
}
Copy after login

FieldName corresponds to the field_name field of the data table (pay attention to the specifications of the data table fields and the definition specifications of the modifier method, otherwise it will cause errors).

In principle, each modifier should only process the data of the corresponding field, but it is allowed to process multiple fields at the same time if necessary.

The following is an example

public function setBirthdayAttr($value, $data)
{
    // 格式化生日数据
    $birthday = strtotime($value);
    // 根据生日判断年龄
    $age = getAgeByBirthday($birthday);
    // 赋值年龄数据
    $this->setAttr('age', $age);
    return $birthday;
}
public function setAgeAttr($value,$data)
{
    return floor($value);
}
Copy after login

The reason why the setAttr method is used is to ensure that the age assignment operation can still go through a separate modifier. If you don’t have additional modifiers, you can also write it as

public function setBirthdayAttr($value, $data)
{
    // 格式化生日数据
    $birthday = strtotime($value);
    // 根据生日判断年龄
    $age = getAgeByBirthday($birthday);
    // 赋值年龄数据
    $this->data['age'] = $age;
    return $birthday;
}
Copy after login

. Note that it must not be written as

$this->age = $age;
Copy after login

because assigning data objects inside the model will cause inefficiency due to confusion with the internal attributes of the model. foreseen consequences.

If you may modify other fields in a certain modifier, be sure to remember that the field modifier you need to modify additionally must have been assigned (or the modifier has been triggered).

How to call

The modifier method does not need to be called manually. After it is defined according to the definition specification, the system will automatically call it under the following circumstances:

·Model object assignment;

·Call the data method of the model, and the second parameter is passed in true;

·Call the save method of the model and pass in the array data;

·Explicitly call the setAttr method of the model;

· defines the automatic completion of this field;

For example, the User model defines setPasswordAttr modification device method.

public function setPasswordAttr($value, $data)
{
    return md5($value);
}
Copy after login

When used as follows, the value of the password field saved to the database will become the value after md5('think').

$user = User::get(1);
$user->password = 'think';
$user->save();
Copy after login

If you do not want to use modifiers but want to manually control the data in some cases, you can try the following method.

$user = User::get(1);
$user->data('password', md5('think'));
$user->save();
Copy after login

It will not be processed by the modifier at this time.

Avoid conflicts

Many developers like to define auto-complete auto (including insert and update) for modifiers.

protected $auto = ['password'];
Copy after login

This is a seemingly clever but very fatal mistake before V5.1.27. Try to avoid it because according to the modifier trigger conditions we gave before, it will cause the modifier to be executed twice. . This will be a catastrophic error and will cause all users to be unable to log in normally after registration.

Solution Cancel the automatic completion setting of the password field, because the modifier will be automatically triggered every time a value is assigned. If there is no assignment, it means that the password has not been modified, and there is no automatic completion.

Auto-complete fields are usually fields that are not in the form, and are generally fields that are automatically processed by the system.

The V5.1.27 version has improved this problem. All modifiers are only allowed to be executed once, and the above problem no longer exists. But it seems to have brought a new problem. Many times, you may want to modify the data in the event of the model.

User::beforeUpdate(function($user) {
    $user->password = md5('think');
});
Copy after login

You will find that in the model beforeUpdate event, the value of the data cannot be modified. The reason is that the model's modifier has been executed during the first assignment, and has been executed during the second assignment. Invalid (will not be executed again).

The solution is to use the data method as I mentioned before without calling the modifier for data assignment operations.

User::beforeUpdate(function($user) {
    $user->data('password', md5('think'));
});
Copy after login

Of course, a better suggestion is to plan the data processing mechanism of modifiers, auto-complete and model events. Do not use multiple mechanisms to modify data at the same time for a field, and the data written to the database should and only be modified. The data modification operation is performed through this method.

Type automatic conversion

If your modifier only performs type conversion on data, you don’t need to define a modifier, but just define the field type directly. .

public function setScoreAttr($value, $data)
{
    return (float) $score;
}
Copy after login

The above modifier method can be directly changed to

protected $type = [
    'score'    =>    'float',
];
Copy after login

If you define a modifier and type for a field at the same time, the modifier takes precedence.

Type definitions can not only define simple data types, but also have some additional uses. For example: json type, array type and object type will be JSON serialized, and the serialize type will serialize the data.

PHP Chinese website has a large number of free ThinkPHP introductory tutorials, everyone is welcome to learn!

This article is reproduced from: https://blog.thinkphp.cn/817548

The above is the detailed content of ThinkPHP: The second of three powerful tools for models (modifier). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:thinkphp.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!