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

  • 2021-07-02 23:40:09
  • OfStack

In the past, before ThinkPHP version 3.1, if it is necessary to set automatic verification or automatic completion, 1 generally speaking, it must be defined in the model or dynamically set attributes by setProperty method. 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:


$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: