Sample code for dynamic setup auto completion and auto validation of new features of ThinkPHP 3.1

  • 2021-07-02 23:42:58
  • OfStack

Before ThinkPHP version 3.1, if you need to set automatic verification or automatic completion, you must define it in the model or dynamically set properties through setProperty method, but the disadvantage of this is that it is not convenient to change and adjust dynamically.

ThinkPHP version 3.1 adds two coherent operations, auto and validate, to the model class to dynamically set auto-completion and auto-validation rules, which can now be used in Action. The sample code is as follows:


$validate = array(
 array(verify,require, Verification code must! ), 
 array(name,, Account name already exists! ,0,unique,1), 
 );
$auto = array ( 
 array(password,md5,1,function) , 
 array(create_time,time,2,function), 
 );
M(User)->auto($auto)->validate($validate)->create();

Among them, the specification of $auto and $validate variables and the definition rules of _ auto and _ validate attributes of model classes are 1, and function calls can also be supported (due to the limitation of PHP itself, functions cannot be called in the attribute definition of classes).

The auto and validate methods must be called before the create method.

Through this 1 improvement, you can use the M method to instantiate the model class and then use dynamic settings to complete automatic verification and automatic completion operations, without relying on the D method.


Related articles: