php连贯操作原理带数据库配置(简单原理)

<?php

class Db{

    private $localhost = null;
    private $username = null;
    private $password = null;
    private $database = null;
    private $prefix = null;
    private $charset = null;
    var $master = true;

    private $sql = array(
        "field" => "",
        "table" => "",
        "where" => "",
        "order" => "",
        "limit" => "",
        "group" => "",
        "having" => "",
    );
    //数据库参数配置
    var $conf = array(
        'localhost' => 'localhost',//localhost
        'username' => 'root',//用户名
        'password' => 'root',//密码
        'database' => 'test',//数据库名字
        'prefix' => '',//数据表前缀
        'charset' => 'utf8',//字符编码
    );

    //默认链接数据库
    public function __construct(){

        $this->localhost = $this->conf['localhost'];
        $this->username = $this->conf['username'];
        $this->password = $this->conf['password'];
        $this->database = $this->conf['database'];
        $this->prefix = $this->conf['prefix'];
        $this->charset = $this->conf['charset'];
        $this->conn = mysqli_connect($this->localhost, $this->username, $this->password);
        mysqli_select_db($this->conn, $this->database);
        mysqli_query($this->conn, 'set names ' . $this->charset);
    }
    
    // __call()方法不存在时触发。$methodName调用的方法名,$args调用的参数(数组形式)
    function __call($methodName, $args)
    {
        // strtolower将第一个参数(代表不存在方法的方法名称),全部转成小写方式,获取方法名称  
        $methodName = strtolower($methodName);
        // 如果调用的方法名和成员属性数组$sql下标对应上,则将第二个参数给数组中下标对应的元素  
        if (array_key_exists($methodName, $this->sql)) {
            $this->sql[$methodName] = $args[0];
        } else {
            echo '调用类' . get_class($this) . '中的方法' . $methodName . '()不存在';
        }
        // 返回自己对象,则可以继续调用本对象中的方法,形成连贯操作  
        return $this;
    }
    // 连贯操作调用field() where() order() limit() group() having()方法,组合sql语句  
    // 输出连贯操作后组合输出一个sql语句,是连贯操作最后的一个方法。{}大括号表示代码块  
    function select()
    {
        $sql = "SELECT {$this->sql['field']} FROM {$this->sql['table']}
                 {$this->sql['where']} {$this->sql['order']} {$this->sql['limit']} 
                 {$this->sql['group']} {$this->sql['having']}";
        $result = mysqli_query($this->conn, $sql);
        $row = mysqli_fetch_all($result);
        return $row;
    }
}

//实例化
$db = new Db();
// 连贯操作  
$result = $db->table('t_eshop')->field('name')->limit('limit 0,10')->order('order by id desc')
    ->select();
print_r($result);
?>

  

posted @ 2019-01-21 17:09  黑白配  阅读(297)  评论(0)    收藏  举报