Preface
Prior to contact programming, although also contact soon (cover face) at the beginning of the original SQL is not skilled, do the project when the direct use, resulting in the beginning of the whole of the SQL knowledge a bit biased, it is hairenbujian, but after learning to slowly start to break out of this pit, a lot of things, such as frame what, If we can only use, the principle does not understand and do not want to understand, then the programming of this will be more narrow, back to the point, ORM, I believe that you should normally develop projects have been useful, such as the PHP laravel framework of ORM or Java Spring ORM Framework, A bit of a summary of ORM, there are the following: ORM is a tool, the tool can indeed solve some of the duplication, simple labor hides the data access details, making our common database interaction simple and easy, without the use of complex SQL statements, Use only the Object-oriented method provided by ORM to modify and delete data, but for complex queries, ORM is still far from satisfied, recently in a report project, found that ORM is really not very good to express, or write native more comfortable point of efficiency, because to perform a variety of matches, Certainly sacrificing some efficiency, but there is currently a cache and lazy load of anything, and the sense of efficiency can be impeccable toss (i)-sql's patchwork
ORM is the body of the string, the user input parameters into a SQL statement, the following code implementation of the common Select, where order by and insert, where the implementation of a multiple table query
The query statement looks like this
$orm =new orm ();
echo $orm->select (["Name" => "ClassID"], ' uname ', ' user ')
->from ([["Name" => "ClassID"], ["Name_class" => "id"]]
->from ([["Name" => "ClassID"], ["Name_class" => "id"]]>orderby (["Class" => "id"], " Desc ");
$orm->insert ([
["id" => ' 123 '],
["Name" => "seven"]
], "News", function ($orm) {
echo Hello World! ";
});
The patchwork effect looks like this:
Hello World, is the callback function output, we can use callback more convenient execution of the business code, here is just learning to simulate our JS callback function, in fact, PHP can also be recalled.
The patchwork code is as follows:
<?php ini_set (' display_errors ', 1);
Ini_set (' error_reporting ', e_all);
$map =function ($items) {if (!is_array ($items)) {return $items;
else {$result = "";
foreach ($items [1] as $item) {if ($result!= "") $result. = ",";
$result. = $item. $this->_aliastb ($item);//A similar news,news_class added to the form after the return $items [0]. $result;
}
}; Class Orm {public $sql =array (' Select ' => ' select ', ' From ' =>array (' from ', Array ()), ' whe Re "=>" where "," by "=>" Order By "," Insertinto "=>" insert into ",//insert operation" Insertf
Ields "=>", "values" => "values");
Public $sql _bak=[];
Public Function __construct () {$this->sql_bak= $this->sql;
The Public Function Select () {$fields =func_get_args (); foreach ($fields as $field) {if (Is_array ($field)) {$get _key=key ($fiELD)//Gets the key of the array, which is actually the name of the table, and also needs to precede the field with the table prefix $this->__add (__function__, $this->_aliastb ($get _key).
$field [$get _key]);
else {$this->__add (__function__, $field);
} return $this;
//Insert Data Public Function Insert () {$params =func_get_args ();//Get variable parameters $fields =[];
$fields _values=[];
$callback =[];
foreach ($params as $param) {if (Is_array ($param)) {//Represents the field and value foreach ($param as $item) to be spliced {
Remove the field name $field =key ($item);
Remove the value of the field $field _value= $item [$field];
Insert the above field and field values into the corresponding array $fields []= $field; When the string is pieced together, judge whether it is a string, and if it is a string, enclose the single quote if (is_string ($field _value)) {$field _value=
"'" $field _value. "'"; } $fields _values[]= $fielD_value;
After the parameters have been processed, construct the patchwork $this->__add ("Insertfields", "Implode ($fields, ', '),") to insert the field.
$this->__add ("Values", ' (' Implode ($fields _values, ', ') ');
///If the string description is the name of the table if (is_string ($param)) {$this->__add ("Insertinto", $param);
} if (Is_callable ($param)) {$callback []= $param;
foreach ($callback as $call) {$call ($this);
return $this;
}//Sort function order by ($STR, $order) {$order = '. $order;
if (Is_array ($STR)) {$TB =key ($STR); $this->__add (__function__, $this->_aliastb ($TB).
$str [$TB]. $order);
else {$this->__add (__function__, $str. $order);
return $this;
///Add alias Public function _aliastb to table ($tbName) {return ' _ '. $tbName; } PUThe Blic function from ($tableName)//processing from procedure {if (Is_array ($tableName)) {//is an array of words that represent multiple table associations if (COUNT ($ TableName)!=2 return $this//parameter value is similar to [[] name =>classid '],[' name_class ']=> ' id '], less than 2 out of meaningful $TB 1=current ($tabl
ENAME);
$TB 2=next ($tableName);
In the first step, the key value of the table is treated as a from parameter $tb 1_key=key ($TB 1);
$TB 1_value= $TB 1[$TB 1_key];
$TB 2_key=key ($TB 2);
$TB 2_value= $TB 2[$TB 2_key];
$this->__add (__function__, $TB 1_key);
$this->__add (__function__, $TB 2_key); The second step, piecing together where conditions $whereString = ' _ '. $TB 1_key. $TB 1_value. ' ='." _ ". $tb 2_key."
$TB 2_value;
$this->where ($whereString);
return $this;
The else {//string will represent a single table query $this->__add (__function__, $tableName);
return $this;
The public function where ($STR) {$this->__add (__function__, $str, "and"); Return $this; The Public Function __add ($key, $str, $spliter = ",")//implements the additive of the string {//call does not exist method, directly returns if (!ARRAY_KEY_EX
Ists ($key, $this->sql)) return; if (Is_array ($this->sql[$key)) {//If the item already exists indicates that we do not do what to do if (!in_array ($str, $this->sql[$key] [
1]) {$this->sql[$key][1][]= $str; } else {//if it is a string, direct string accumulation//if (Trim ($this->sql[$key])!= $key) if (preg_
Replace ('/\s/', ', $this->sql[$key])!= $key && preg_replace ("/\s/", ', $this->sql[$key])!= "")
$this->sql[$key].= $spliter;
$this->sql[$key].= $str;
The Public Function __tostring () {Global $map;
$map =closure::bind ($map, $this);
$filter =function ($value, $key) {//if (!is_string ($value)) return true;
if (Is_array ($value)) {if (count ($value [1]) >0) return true; return false; //If an empty string does not participate in the additive if (Preg_replace ("/\s/", ", $value) = = $key | | preg_replace ("/\s/"," ", $value) = =
"") return false;
return true;
};
$this->sql=array_filter ($this->sql, $filter, Array_filter_use_both);
$res =array_map ($map, Array_values ($this->sql))//$this->sql= $this->sql_bak; Return implode (Array_values ($res), ")//Rebuild the new array into a string}}
It involves some of the more often rarely contact functions such as array_map,array_filter, at that time since php7 out, PHP is not only to do the site, or to understand some functions of the magical. The next section will introduce, piecing together strings and PDO combinations, and make a simple demo.