thinkphp3.2.0 Setinc method source code comprehensive analysis PHP instance

Source: Internet
Author: User
The following small series for you to share a thinkphp3.2.0 Setinc method source comprehensive analysis, with a very good reference value, I hope to be helpful to everyone. Let's take a look at it with a little knitting.

Let's take a look at the official example of Setinc:

Requires a field and a self-increment value (default = 1)

Let's step through the following example to analyze how his bottom layer is implemented:

<?phpnamespace home\controller;use Think\controller;class TestController extends Controller {public  function Test () {    $TB _test = M (' test ');    $TB _test->where ([' ID ' =>1])->setinc (' Test_number ', 2); Add 2 dumps at a time    ($TB _test->getlastsql ());    String ("UPDATE" Tb_test ' SET ' Test_number ' =test_number+2 WHERE (' id ' = 1) '}  }

The first step must be to find the source of the Setinc method:

Here I used the Phpstrom global search method, found the Setinc is under the proj\thinkphp\library\think\model.class.php

/**   * Field value growth   * @access public   * @param string $field field name   * @param integer $step growth value   * @return boolean
  */Public  function Setinc ($field, $step =1) {    return $this->setfield ($field, Array (' exp ', $field. ') + '. $step));  }

You can see that the SetField method is used here, and then set with the exp custom expression $field = $field + $step Here, we know a little bit about the principle.

But the question came again. SetField how to achieve it? Under the same file, find the SetField method:

/**   * Setting a field value for a record   * support for using database fields and methods   * @access public   * @param string|array $field field name   * @param String $value field Value   * @return Boolean */public  function SetField ($field, $value = ") {    if (Is_array ($ field) {      $data      =  $field;    } else{      $data [$field]  =  $value;    }    return $this->save ($data);  }

Here we see the commonly used save method, where the $data [$field] = $value; is actually $data [' test_number '] = Array ("exp", "test_number+2")

Then look at the most common save methods:

/** * Save Data * @access public * @param mixed $data data * @param array $options expression * @return Boolean */public F Unction Save ($data = ", $options =array ()) {if (empty ($data)) {//does not pass data, gets the value of the current data object if (!empty ($this->data))        {$data = $this->data;      Reset data $this->data = Array ();        }else{$this->error = L (' _data_type_invalid_ ');      return false;    }}//Data processing $data = $this->_facade ($data);    Parse expression $options = $this->_parseoptions ($options);    $PK = $this->getpk (); if (!isset ($options [' where '])) {//If the primary key data exists automatically as the update condition if (isset ($data [$pk]) {$where [$pk] = $data [$        PK];        $options [' where '] = $where;      Unset ($data [$PK]);        }else{//Do not perform $this->error = L (' _operation_wrong_ ') if there are no update conditions;      return false; }} if (Is_array ($options [' where ']) && isset ($options [' where '] [$pk]) {$pkValue = $options [' WHERE ' [$PK];    } if (false = = = $this->_before_update ($data, $options)) {return false;    } $result = $this->db->update ($data, $options);      if (false!== $result) {if (Isset ($pkValue)) $data [$PK] = $pkValue;    $this->_after_update ($data, $options);  } return $result; }

The most important is $options = $this->_parseoptions ($options), and $result = $this->db->update ($data, $options); The former converts the parameters into a string array for stitching SQL, which calls the Update method under proj\tptest\thinkphp\library\think\db.class.php:

/**   * Update record   * @access public   * @param mixed $data data   * @param array $options expression   * @return false | inte GER   *  /Public Function update ($DATA, $options) {    $this->model =  $options [' model '];    $sql  = ' UPDATE '      . $this->parsetable ($options [' table '])      . $this->parseset ($data)      . $this- >parsewhere (!empty ($options [' where '])? $options [' WHERE ']: ')      . $this->parseorder (!empty ($options [' Order '])? $options [' Order ']:      $this->parselimit ($options [' limit '])? $options [' Limit ']: ')      . $this->parselock (Isset ($options [' Lock '])? $options [' Lock ']:false]      . $this->parsecomment (!empty ($options [' comment '])? $options [' Comment ']: ');    return $this->execute ($sql, $this->parsebind (!empty ($options [' bind ')]? $options [' Bind ']:array ()]);  }

In the end, we used the Execute method of the Proj\thinkphp\library\think\db\driver\mysql.class.php driver class.

/**   * EXECUTE statement   * @access public   * @param string $str SQL instruction   * @return integer|false  */Public function Execute ($str) {    $this->initconnect (true);    if (! $this->_linkid) return false;    $this->querystr = $str;    Releases the previous query result    if ($this->queryid) {  $this->free ();  }    N (' Db_write ', 1);    Record start execution time    G (' querystarttime ');    $result =  mysql_query ($str, $this->_linkid);    $this->debug ();    if (false = = = $result) {      $this->error ();      return false;    } else {      $this->numrows = mysql_affected_rows ($this->_linkid);      $this->lastinsid = mysql_insert_id ($this->_linkid);      return $this->numrows;    }  }

Finally execute the SQL statement with the lowest mysql_query.

So far, the source of the Setinc has been roughly over. Presumably everyone knows a little more about how setinc is implemented.

Above this article thinkphp3.2.0 Setinc method source Comprehensive analysis is a small part of the whole content to share to everyone, I hope to give you a reference, but also hope that we support a lot of PHP Chinese web.

Related recommendations:

PHP's example of using binary to save user state PHP Tips

Php+redis Message Queue Implementation High concurrency instances of the registered population statistics PHP instance

Laravel ORM only opens created_at several ways to summarize PHP instances

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.