php 链式操作详解

链式操作,在我们用的php框架中经常能用到,特别是tp laravel 和yii 这些model类。

如laravel里面:

$user = new User();   
$user->where('条件')->order('排序')->get();//获取结果之类的。这就是所谓的链式操作

链式操作的好处就是。多行代码能节省写成一行,(代码简洁)利于阅读(可读性强)(方便维护)(连贯,并且语义简单)

下面我们看简单的代码实现,我写了个简单的demo。分为两个文件

一个是封装好的链式操作model类 ,一个是 调用者。

封装好的链式操作model类如下(文件名mode.php):

<?php
/**
 * 作者:UncleFreak,星辰
 * 博客:www.z88j.com
 * 时间:20201126
 * Class mode
 */

class mode
{
    /**
     * 查询
     * @param $where
     * @return $this
     */
    public function where($where){
        $this->value .= $where;
        return $this;
    }

    /**
     * 排序
     * @param $where
     * @return $this
     */
    public function order($order){
        $this->value .= $order;
        return $this;
    }

    /**
     *  分组
     * @param $group
     * @return $this
     */
    public function groupBy($group){
        $this->value .= $group;
        return $this;
    }

    /**
     *  多少条数据
     * @param $where
     * @return $this
     */
    public function limit($limit){
        $this->value .= $limit;
        return $this;
    }

    public function get(){
        return $this;
    }
}
php 链式操作详解

下面是一个调用者php文件(文件名main.php):

<?php

/**
 * 作者:UncleFreak,星辰
 * 博客:www.z88j.com
 * 时间:20201126
 * Class mode
 */

require_once "mode.php";

class main
{
    public function run(){
        $mode = new mode();
        $res = $mode->where("id = 1")//php里面的链式操作
            ->where("username = '111'")
            ->limit(10)
            ->get();
        return $res;
    }
}
$run = new main();
$data = $run->run();
var_dump($data->value);
php 链式操作详解

转载请声明来源:www.z88j.com

原创文章,作者:星辰,如若转载,请注明出处:https://www.z88j.com/81.html

(4)
打赏 微信扫一扫 微信扫一扫
上一篇 2020年11月23日 下午8:00
下一篇 2020年12月2日 上午12:14

相关推荐

发表回复

登录后才能评论

Warning: error_log(/www/wwwroot/www.z88j.com/wp-content/plugins/spider-analyser/#log/log-2912.txt): failed to open stream: No such file or directory in /www/wwwroot/www.z88j.com/wp-content/plugins/spider-analyser/spider.class.php on line 2900