本文借鉴文章:Javascript、C#、php、asp、python 等语言的链式操作的实现
一、什么是链式操作
把需要的下一步操作的对象通过上一步操作返回回来。使完成某些功能具有持续性。
二、链式操作优点
代码更精简优雅。链式操作能大大精简代码量,多项操作一行代码一气呵成,搞定;链式操作应用场景除了前端jquery方面的操作dom,后端语言PHP、Go、Python、Java等web框架都有orm的身影.
三、各种语言的链式操作实现
1.Go链式操作ORM同Java、PHP、Python可以是一样的
//goChain.go
package main
import (
"fmt"
)
type link struct {
Table string
Limit string
Where string
Field string
}
func (o *link) setTable(table string) *link {
o.Table = table
return o
}
func (o *link) setLimit(limit string) *link {
o.Limit = limit
return o
}
func (o *link) setWhere(where string) *link {
o.Where = where
return o
}
func (o *link) setField(field string) *link {
o.Field = field
return o
}
func (o *link) print() {
fmt.Printf("SELECT %s FROM %s WHERE %s LIMIT 0,%d", o.Field, o.Table, o.Where, o.Limit)
}
func main() {
o := link{}
o.setTable("user").setField("id, username, password ").setWhere(" id = 1").setLimit("1").print()
//输出结果:SELECT id, username, password FROM user WHERE id = 1 LIMIT 0,%!d(string=1)
}
2.实现链式操作可以使用PHP的魔术方法_call。但是我这里实现还是愿意一开始说的返回对象本身的思路没有用到_call
<?php
//phpChain.php
class Link
{
static public $_garr= array(
'table'=>'',
'limit' =>0,
'where' => ' 1=1 ',
'field' => ' '
);
function __construct($table)
{
self::$_garr['table'] = $table ;
}
public function where($where='')
{
self::$_garr['where'].= ' and '.$where ;
return $this;
}
public function field($field)
{
self::$_garr['field'] = $field ;
return $this;
}
public function top($top)
{
self::$_garr['limit'] = $top;
return $this;
}
public function query()
{
$sql_arr = self::$_garr;
$sql = "SELECT {$sql_arr['field']} FROM {$sql_arr['table']} WHERE {$sql_arr['where']} LIMIT 0, {$sql_arr['limit']}";
return $sql;
}
};
$db = new Link("user");
$sql = $db->top(10)
->field("id, username, password ")
->where(" id = 1")
->query();
print($sql); //结果:SELECT id, username, password FROM user WHERE 1=1 and id = 1 LIMIT 0, 10
?>
3.Python链式操作代码
#PythonChain.py
class Link:
def __init__(self, table):
self.table = table
def where(self, where):
self.where = 'and ' +where
return self;
def field(self, field):
self.field = field
return self
def top(self, top):
self.limit = top
return self;
def query(self):
sql = 'SELECT '+self.field+' FROM '+self.table+' WHERE 1=1 '+ self.where+' limit 0,'+self.limit
return sql
p = Link('user')
sql = p.top(str(10)).field('id, username, password').where('id=1').query()
print(sql)
#输出结果:SELECT id, username, password FROM user WHERE 1=1 and id=1 limit 0,10
3.Java链式操作代码
//Link.java
public class Link {
private String table;
private int limit;
private String where;
private String field;
public Link setTable(String table) {
this.table = table;
return this;
}
public Link setLimit(int limit) {
this.limit = limit;
return this;
}
public Link setWhere(String where) {
this.where = where;
return this;
}
public Link setField(String field) {
this.field = field;
return this;
}
public void printSql() {
//System.out.println(this.address);
System.out.println(" SELECT "+this.field+"FROM "+this.table+" WHERE "+this.where+" LIMIT 0,"+this.limit);
//return this;
}
}
Test.java测试代码:
//Test.java
public class Test {
public static void main(String[] args) {
Link link1 = new Link();
link1.setTable("user").setLimit(10).setField(" id, username, password ").setWhere(" id = 1").printSql();
//结果: SELECT id, username, password FROM user WHERE id = 1 LIMIT 0,10
}
}
4.Javascript 的链式操作大家最熟悉不过了,jquery 的整个框架就是链式操作实现,我这里写的demo 当然跟jquery 实现的思路不是一致的,jquery具体实现方式可以看jquery源码。
var Link = function (table){
this.sql = {
"table" : "",
"where" : " 1=1 ",
"limit" : 0,
"field" : ""
}
this.sql.table = table;
}
Link.prototype = {
where : function (where)
{
this.sql.where += " and "+ where;
return this;
},
field : function (field)
{
this.sql.field = field;
return this;
},
top : function (limit)
{
this.sql.limit = limit;
return this;
},
query : function ()
{
var sqlstr = "SELECT "+this.sql.field+" FROM "+this.sql.table
+" WHERE "+ this.sql.where+ " LIMIT 0,"+this.sql.limit;
return sqlstr;
}
}
var db = new Link("user");
var $val = db.where(" id = 1")
.top(10)
.field(" id, username , password")
.query();
console.log($val);
完整版HTML代码:
<!DOCTYPE html>
<!-- JsChain.html页面 -->
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>JS链式操作</title>
<link rel="stylesheet" href="">
</head>
<body>
<script type="text/javascript">
window.onload=function(){
var Link = function (table){
this.sql = {
"table" : "",
"where" : " 1=1 ",
"limit" : 0,
"field" : ""
}
this.sql.table = table;
}
Link.prototype = {
where : function (where)
{
this.sql.where += " and "+ where;
return this;
},
field : function (field)
{
this.sql.field = field;
return this;
},
top : function (limit)
{
this.sql.limit = limit;
return this;
},
query : function ()
{
var sqlstr = "SELECT "+this.sql.field+" FROM "+this.sql.table
+" WHERE "+ this.sql.where+ " LIMIT 0,"+this.sql.limit;
return sqlstr;
}
}
var db = new Link("user");
var $val = db.where(" id = 1")
.top(10)
.field(" id, username , password")
.query();
console.log($val);
//这里需要打开浏览器控制台
//输出结果: SELECT id, username , password FROM user WHERE 1=1 and id = 1 LIMIT 0,10
}
</script>
</body>
</html>
5.C# 实现链式,主要通过其.net 框架提供的扩展方法,代码如下
using System;
namespace ConsoleApplication1
{
public class sqlHelp
{
public sqlHelp (string table) {
this.table = table;
}
public string where = "";
public string field = "";
public int limit = 0;
public string table = "";
}
static class LinkExtended
{
public static sqlHelp Where(this sqlHelp h, string where)
{
h.where += " and"+ where;
return h;
}
public static sqlHelp Top(this sqlHelp h, int limit)
{
h.limit = limit;
return h;
}
public static sqlHelp Field(this sqlHelp h, string field)
{
h.field = field;
return h;
}
public static string Query(this sqlHelp h)
{
string sql = string.Format("SELECT {0} FROM {1} WHERE 1=1 {2} LIMIT 0, {3}",
h.field, h.table, h.where, h.limit);
return sql;
}
}
class Program
{
static void Main(string[] args)
{
sqlHelp db = new sqlHelp("user");
string sql = db.Top(10)
.Field("id, username, password")
.Where(" id =1")
.Query();
Console.WriteLine(sql);
Console.ReadLine();
}
}
}
6.asp(vbscript)这个我一直在网上搜索资料也没见有人写过, 我自认为我这里写出来的是全网第一份(当然可能人家有我没找到而已,呵呵所以自我陶醉下),因为vbscript 本身的类是非常弱的,但是也提供了 defalut 和 me 这样好用的特性,所以实现链式也不是什么难事( 如果熟练vbscript 的朋友可以能会想到 with .. end with 语言 其实这个语言本身有点链式的味道,但是思路上不叫链式操作)
Class Link
'声明一个全局字典
Dim sqlD
public Default function construct(table)
Set sqlD = CreateObject("Scripting.Dictionary")
Call sqlD.add("table", table)
Set construct = me
End function
Public Function where(whereStr)
Call sqlD.add("where", whereStr)
Set Where = me
End Function
Public Function top(limit)
Call sqlD.add("limit", limit)
Set top = me
End Function
Public Function field(fieldStr)
Call sqlD.add("field", fieldStr)
Set field = me
End Function
Public Function query()
Dim sql
sql = "SELECT "& sqlD.item("field")&" FROM "&sqlD.item("table")&" WEHRE "&sqlD.item("where")
query = sql
End function
End Class
Dim db, sql
Set db = (New Link)("user")
sql = db.top(10).field("id, username, password").Where(" id = 1").query()
msgbox sql
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。