php链式操作 2018-09-05

    首先我们创建一个类

    就叫database吧


    然后在每个要被链的里面返回$this 也就是把当前类再次return出来, 例如我们->where

     我们只是把where条件传到 where方法里面去,然后经过处理,存在类里面的a数组里。

    然后把当前类返回回去。 然后再进行下一个链式操作,如果没有链操作的话,我们最后连接上要执行的方法。

    例如tp里面可能是find() count() select() sum() .....

    而我们这里就简洁点用query 随便起名字吧,,,,  然后query 再把a变量里面的各种属性堆积拼接成一条sql语句。


    image.png 


    image.png



    OK, 这样的话我们执行出来的sql 语句是  

    image.png


    不知道是不是有木有bug  因为我也没具体跑进数据库查看下。。 当然如果我们有写配置文件的话,是不是可以再加个前缀?没错,可以自己扩展,并连接链接上mysql 。 像tp的里面就很丰富。大家有闲心到时可以看下他是怎么来实现链式操作的呢?


    自己讲的可能不好,不太会说明,大概就是这样,你们自己看着代码试试?


    <?php
    
    class DataBase {
    
        private $a = [];
    
        public function __construct($param) {
            $this->a['table'] = $param;
        }
    
        public function where($param) {
            $this->a['where'] = ' where ' . $param;
            return $this;
        }
    
        public function orderBy($param) {
            $this->a['order'] = ' order by ' . $param;
            return $this;
        }
    
        public function limit($param) {
            $this->a['limit'] = ' limit ' . $param;
            return $this;
        }
    
        public function query() {
    
            return 'select * from  ' . $this->a['table'] .
                    (isset($this->a['where']) ? $this->a['where'] : '') .
                    (isset($this->a['order']) ? $this->a['order'] : '') .
                    (isset($this->a['limit']) ? $this->a['limit'] : '');
        }
    
    }
    
    $obj = new DataBase('test');
    
    //链式操作
    echo $obj->where('id >10 and type = 1')->limit('0,10')->orderBy('id desc')->query();
    echo '<br />';
    $obj2 = new DataBase('aa');
    
    echo $obj2->orderBy('id desc')->limit('0,10')->query();