Javascript、C#、php、asp、python 等语言的链式操作的实现

一、什么是链式操作

  把需要的下一步操作的对象通过上一步操作返回回来。使完成某些功能具有持续性。

二、链式操作优点

  代码更精简优雅。链式操作能大大精简代码量,多项操作一行代码一气呵成,搞定;

  链式操作应用场景除了想前端jquery方面的操作dom,后端web框架,在开发orm相关的框架也是常常用到

三、各种语言的链式操作实现

  以下根据简单的实现数据库查询的类似实现一些web框架的 orm。查询类的各种DEMO

  1、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);

2、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();

        }
    }

}

3、php 实现链式操作可以使用php的魔术方法_call。但是我这里实现还是愿意一开始说的返回对象本身的思路没有用到_call。

<?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);

?>

 4、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

 

 5、python 实现链式非常的方便简单

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)

 

四、其他需要待续

  echosong 在码农生涯中,暂时只用到了以上些语言,所以目前也只实现了以上的语言链式操作,欢迎大家补充其他语言链式操作demo

posted @ 2015-06-20 23:34  EchoSong  阅读(1399)  评论(3编辑  收藏  举报