Php consistent operation implementation, php
We often use this code when coding some frameworks (such as ThinkPHP.
M ('user')-> where (array ('id' => 1)-> field ('name')-> select ();
This not only facilitates coding, but also makes people "happy. Okay, I will not talk about it anymore. Let's see how it works?
<? Php
// Database operation base class [PS: Main Function coherent function implementation]
Class Db {
// This attribute defines the method name for consistent operations
Public $ SQL = array (
"Field" => "",
"Where" => "",
"Order" => "",
"Limit" => "",
"Group" => "",
"Having" => "",
);
/**
* For a coherent operation, the field () where () order () limit () group () having () method is called and combined into an SQL statement.
* This method is a PHP magic method. It is automatically called when a method does not exist in the class is called.
* @ Param $ methodName receives the string of the method name when calling a method that does not exist.
* @ Param $ args when calling a method that does not exist, the parameter of this method is received as an array.
*/
Function _ call ($ methodName, $ args ){
// Convert the name of the method to be requested to lowercase
$ MethodName = strtolower ($ methodName );
// If the request method name corresponds to the member attribute array $ SQL subscript, the second parameter is assigned to the array "element corresponding to the subscript"
If (isset ($ this-> SQL [$ methodName]) {
$ This-> SQL [$ methodName] = $ args [0];
} Else {
Echo '. $ methodName.' () method in 'Call class'. get_class ($ this). 'does not exist ';
}
// Return the object. You can continue to call the methods in this object to form a coherent operation.
Return $ this;
}
/**
* Concatenate a select SQL statement using this method. [PS: This method terminates a coherent operation and puts it at the end of a coherent operation]
*/
Function select (){
// Concatenate an SQL string according to the select syntax [PS: You can execute "help select;" in the mysql command line to view its syntax structure]
$ SQL = "SELECT {$ this-> SQL ['field']} FROM test {$ this-> SQL ['where']} {$ this-> SQL ['group ']} {$ this-> SQL ['having']} {$ this-> SQL ['order']} {$ this-> SQL ['limit']}";
Echo $ SQL;
}
}
$ Obj = new db ();
$ Obj-> field ('name, sex, address ')-> where ('where name = "gongwen"')-> limit ('limit 1 ') -> select ();
// Output: SELECT name, sex, address FROM test where name = gongwen limit 1