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; }
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); }
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; }
. Note that it must not be written as
$this->age = $age;
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); }
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();
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();
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'];
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'); });
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')); });
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; }
The above modifier method can be directly changed to
protected $type = [ 'score' => 'float', ];
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!

The article discusses ThinkPHP's built-in testing framework, highlighting its key features like unit and integration testing, and how it enhances application reliability through early bug detection and improved code quality.

Article discusses using ThinkPHP for real-time stock market data feeds, focusing on setup, data accuracy, optimization, and security measures.

The article discusses key considerations for using ThinkPHP in serverless architectures, focusing on performance optimization, stateless design, and security. It highlights benefits like cost efficiency and scalability, but also addresses challenges

The article discusses implementing service discovery and load balancing in ThinkPHP microservices, focusing on setup, best practices, integration methods, and recommended tools.[159 characters]

ThinkPHP's IoC container offers advanced features like lazy loading, contextual binding, and method injection for efficient dependency management in PHP apps.Character count: 159

The article discusses using ThinkPHP to build real-time collaboration tools, focusing on setup, WebSocket integration, and security best practices.

ThinkPHP benefits SaaS apps with its lightweight design, MVC architecture, and extensibility. It enhances scalability, speeds development, and improves security through various features.

The article outlines building a distributed task queue system using ThinkPHP and RabbitMQ, focusing on installation, configuration, task management, and scalability. Key issues include ensuring high availability, avoiding common pitfalls like imprope


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

WebStorm Mac version
Useful JavaScript development tools