Php consistent operation implementation. Php consistent operation implementation we often use this code when using some frameworks (such as ThinkPHP) encoding. M (User)-where (array (id1)-field (name)-select ();
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?
// 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 = "guoyu"')-> limit ('limit 1 ') -> select ();
// Output: SELECT name, sex, address FROM test where name = guoyulimit 1
Coding we often use this code when using some frameworks (such as ThinkPHP) encoding. M (User)-where (array (id = 1)-field (name)-select (); this not only facilitates encoding...