Principle and Usage Analysis of Automatic Filling in thinkPHP Framework

  • 2021-09-16 06:22:50
  • OfStack

This paper analyzes the principle and usage of thinkPHP framework automatic filling with examples. Share it for your reference, as follows:

thinkphp has 1 method to automatically populate fields

The population rules are as follows


array(
   array( Completion field 1, Completion rule ,[ Completion condition , Additional rule ]),
   array( Completion field 2, Completion rule ,[ Completion condition , Additional rule ]),
   ......
);

Note: After studying the source code, it is found that there is actually a fourth parameter, which is used to pass parameters to functions or callback methods. Parameter 1 defaults to the field value, such as:


array('mobile','trim',3,'function', Parameter 2 , parameter 3'),

Verify payment dynamic and static

Static validation

Predefine the automatic validation rules of the model in the model class, and use the create Method is automatically validated.

The following is an official example

1. First define the validation rules in the model


namespace Home\Model;
use Think\Model;
class UserModel extends Model{
   protected $_auto = array (
     array('status','1'), //  When adding, put status Field is set to 1
     array('password','md5',3,'function') , //  Right password Fields are created when adding and editing md5 Function processing 
     array('name','getName',3,'callback'), //  Right name Callback when fields are added and edited getName Method 
     array('update_time','time',2,'function'), //  Right update_time The current timestamp is written to the field when it is updated 
   );
}

2. Use the create Method automatically populates


$User = D("User"); //  Instantiation User Object 
if (!$User->create()){ //  Create a data object 
   //  If the creation fails   Indicates that the authentication failed   Output error message 
   exit($User->getError());
}else{
   //  Verify through   Write new data 
   $User->add();
}

Dynamic verification

The following is an official example


$rules = array (
  array('status','1'), //  When adding, put status Field is set to 1
  array('password','md5',3,'function') , //  Right password Fields are created when adding and editing md5 Function processing 
  array('update_time','time',2,'function'), //  Right update_time The current timestamp is written to the field when it is updated 
);
$User = M('User');
$User->auto($rules)->create();
$User->add();

Here's the core code analysis:

When the create method is called, the autoOperation Method, as follows


/**
 *  Automatic form processing 
 * @access public
 * @param array $data  Create data 
 * @param string $type  Create type 
 * @return mixed
 */
private function autoOperation(&$data,$type) {
  if(!empty($this->options['auto'])) {
    $_auto  =  $this->options['auto'];
    unset($this->options['auto']);
  }elseif(!empty($this->_auto)){
    $_auto  =  $this->_auto;
  }
  //  Autofill 
  if(isset($_auto)) {
    foreach ($_auto as $auto){
      //  Fill factor definition format 
      // array('field',' Fill in content ',' Filling condition ',' Additional rule ',[ Additional parameters ])
      if(empty($auto[2])) $auto[2] = self::MODEL_INSERT; //  It is automatically populated when adding by default 
      // The judgment here is the key, $type Is the current operation state with a value of 1 Indicates an insert with a value of 2 Indicates that it is an update 
      // If the current $type The status value is equal to the set value $auto[2] Or $auto[2] The value of is 3 That represents the need to populate 
      if( $type == $auto[2] || $auto[2] == self::MODEL_BOTH) {
        if(empty($auto[3])) $auto[3] = 'string';
        switch(trim($auto[3])) {
          case 'function':  //  Populating with functions   Field as a parameter 
          case 'callback': //  Use the callback method 
            $args = isset($auto[4])?(array)$auto[4]:array();
            if(isset($data[$auto[0]])) {
              array_unshift($args,$data[$auto[0]]);
            }
            if('function'==$auto[3]) {
              $data[$auto[0]] = call_user_func_array($auto[1], $args);
            }else{
              $data[$auto[0]] = call_user_func_array(array(&$this,$auto[1]), $args);
            }
            break;
          case 'field':  //  Fill with the values of other fields 
            $data[$auto[0]] = $data[$auto[1]];
            break;
          case 'ignore': //  Empty Ignore 
            if($auto[1]===$data[$auto[0]])
              unset($data[$auto[0]]);
            break;
          case 'string':
          default: //  Padded as a string by default 
            $data[$auto[0]] = $auto[1];
        }
        if(isset($data[$auto[0]]) && false === $data[$auto[0]] )  unset($data[$auto[0]]);
      }
    }
  }
  return $data;
}

For more readers interested in thinkPHP related contents, please check the topics of this site: "ThinkPHP Introduction Tutorial", "thinkPHP Template Operation Skills Summary", "ThinkPHP Common Methods Summary", "codeigniter Introduction Tutorial", "CI (CodeIgniter) Framework Advanced Tutorial", "Zend FrameWork Framework Introduction Tutorial" and "PHP Template Technology Summary".

I hope this article is helpful to the PHP programming based on ThinkPHP framework.


Related articles: