PHP Consistent Operation implementation
We often use this code when we are coding with frameworks such as thinkphp.
M (' User ')->where (array (' ID ' =>1))->field (' name ')->select ();
This is not only conducive to coding, but also can make people "happy" it. Well, not much to say. Let's see how it's implemented, right?
Database operation base class [PS: Main functional coherence function implementation]
Class db{
This property defines the name of the method to implement a coherent operation
Public $sql = Array (
"Field" = "",
"WHERE" = "",
"Order" = "" ",
"Limit" = "",
"Group" and "" ",
"Having" and "=",
);
/**
* When a coherent operation is invoked, the field () where () order () limit () group () method is called and combined into an SQL statement
* This method is a PHP magic method that calls this method automatically when a method that does not exist in the class is called
* @param a string that receives the name of the method when $methodName call a method that does not exist
* @param $args call a non-existent method, receive the parameter of this method, receive it as an array
*/
function __call ($methodName, $args) {
To convert the method name to the request, unify to lowercase
$methodName =strtolower ($methodName);
If the request method name corresponds to a member attribute array $sql subscript, then the second parameter is assigned to the element corresponding to the subscript in the array.
if (Isset ($this->sql[$methodName])) {
$this->sql[$methodName]= $args [0];
}else{
Echo ' calls class '. Get_class ($this). ' In the '. $methodName. ' () method does not exist ';
}
Returns the object so that you can continue to invoke the methods in this object to form a coherent operation
return $this;
}
/**
* Use this method to splice into a select SQL statement; [PS: This method ends a coherent operation and is placed on the last side of a coherent operation]
*/
function Select () {
concatenation of SQL strings by the SELECT syntax [PS: You can perform a "help select" on the MySQL command line; View its grammatical 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
http://www.bkjia.com/PHPjc/986703.html www.bkjia.com true http://www.bkjia.com/PHPjc/986703.html techarticle PHP's coherent operation enables us to use some of the frameworks (such as thinkphp) to encode code that is commonly used. M (User)-where (Array (id=1))-field (name)-select (); This not only facilitates coding ...