php學習之Model類


<?php

$config = include 'config.php'; //引入數據庫配置文件
$model = new Model($config);
//測試案例
// $saveData=['username'=>'張三','mobile'=>12334123];
// echo $model->table('user')->insert($saveData);
// var_dump($model->table('user')->where('id=5')->delete());
// var_dump($model->table('user')->limit('0,6')->field('username,mobile')->where('id>1')->order('id desc')->select());
// $updateData=['username'=>'張三'];
// var_dump($model->table('user')->where('id=3')->update($updateData));
// var_dump($model->table('user')->max('mobile'));
// var_dump($model->table('user')->getByUserName('張三'));
// var_dump($model->sql);

class Model
{
    //主機名
    protected $host;
    //用戶名
    protected $user;
    //密碼
    protected $pwd;
    //數據庫名
    protected $dbname;
    //字符集
    protected $charset;
    //數據庫前綴
    protected $prefix;

    //數據庫連接資源
    protected $link;
    //數據表名       這里可以自己指定表名
    protected $tableName;

    //sql語句
    protected $sql;
    //操作數組   存放的就是所有的查詢條件
    protected $options;

    /**
     * 構造方法,對成員變量進行初始化
     *
     * @param [type] $config
     */
    function __construct($config)
    {
        //對成員變量一一進行初始化
        $this->host = $config['DB_HOST'];
        $this->user = $config['DB_USER'];
        $this->pwd = $config['DB_PWD'];
        $this->dbname = $config['DB_NAME'];
        $this->charset = $config['DB_CHARSET'];
        $this->prefix = $config['DB_PREFIX'];

        //連接數據庫
        $this->link = $this->connect();

        //得到數據表名  user===>UserModel
        $this->tableName = $this->getTableName();

        //初始化option數組
        $this->initOptions();
    }

    /**
     * 連接數據庫
     *
     * @return void
     */
    protected function connect()
    {
        $link = mysqli_connect($this->host, $this->user, $this->pwd);
        if (!$link) {
            die('數據庫連接失敗');
        }
        //選擇數據庫
        mysqli_select_db($link, $this->dbname);
        //設置字符集
        mysqli_set_charset($link, $this->charset);
        //返回連接成功的資源
        return $link;
    }

    /**
     * 得到數據表名
     *
     * @return void
     */
    protected function getTableName()
    {
        //第一種,如果設置了成員變量,那么通過成員變量來得到表名
        if (!empty($this->tableName)) {
            return $this->prefix . $this->tableName;
        }
        //第二種,如果沒有設置成員變量,那么通過類名來得到表名
        //得到當前類名字符串
        $className = get_class($this);
        //user  UserModel   goods  GoodsModel
        $table = strtolower(substr($className, 0, -5));
        return $this->prefix . $table;
    }

    /**
     * 初始化option數組
     *
     * @return void
     */
    protected function initOptions()
    {
        $arr = ['where', 'table', 'field', 'order', 'group', 'having', 'limit'];
        foreach ($arr as $value) {
            //將options數組中這些鍵對應的值全部清空
            $this->options[$value] = '';
            if ($value === 'table') {
                $this->options[$value] = $this->tableName;
            } elseif ($value == 'field') {
                $this->options[$value] = '*';
            }
        }
    }

    /**
     * field方法
     *
     * @param [type] $field
     * @return void
     */
    function field($field)
    {
        //如果不為空,再進行處理
        if (!empty($field)) {
            if (is_string($field)) {
                $this->options['field'] = $field;
            } elseif (is_array($field)) {
                $this->options['field'] = join(',', $field);
            }
        }
        return $this;
    }

    /**
     * //table方法
     *
     * @param [type] $table
     * @return void
     */
    function table($table)
    {
        if (!empty($table)) {
            $this->options['table'] = $this->prefix . $table;
        }
        return $this;
    }

    /**
     * where方法
     *
     * @param [type] $where
     * @return void
     */
    function where($where)
    {
        if (!empty($where)) {
            $this->options['where'] = 'where ' . $where;
        }
        return $this;
    }

    /**
     * group方法
     *
     * @param [type] $group
     * @return void
     */
    function group($group)
    {
        if (!empty($group)) {
            $this->options['group'] = 'group by ' . $group;
        }
        return $this;
    }

    /**
     * having方法
     *
     * @param [type] $having
     * @return void
     */
    function having($having)
    {
        if (!empty($having)) {
            $this->options['having'] = 'having ' . $having;
        }
        return $this;
    }

    /**
     * order方法
     *
     * @param [type] $order
     * @return void
     */
    function order($order)
    {
        if (!empty($order)) {
            $this->options['order'] = 'order by ' . $order;
        }
        return $this;
    }

    /**
     * limit方法
     *
     * @param [type] $limit
     * @return void
     */
    function limit($limit)
    {
        if (!empty($limit)) {
            if (is_string($limit)) {
                $this->options['limit'] = 'limit ' . $limit;
            } elseif (is_array($limit)) {
                $this->options['limit'] = 'limit ' . join(',', $limit);
            }
        }
        return $this;
    }

    /**
     * select方法
     *
     * @return void
     */
    function select()
    {
        //先預寫一個帶占位符的sql語句
        $sql = 'select %FIELD% from %TABLE% %WHERE% %GROUP% %HAVING% %ORDER% %LIMIT%';
        //將options中對應的值依次的替換上面的占位符
        $sql = str_replace(
            ['%FIELD%', '%TABLE%', '%WHERE%', '%GROUP%', '%HAVING%', '%ORDER%', '%LIMIT%'],
            [
                $this->options['field'], $this->options['table'], $this->options['where'], $this->options['group'],
                $this->options['having'], $this->options['order'], $this->options['limit']
            ],
            $sql
        );
        //保存一份sql語句
        $this->sql = $sql;
        //執行sql語句
        return $this->query($sql);
    }

    /**
     * query
     *
     * @param [type] $sql
     * @return void
     */
    function query($sql)
    {
        //清空option數組中的值
        $this->initOptions();
        //執行sql語句
        $result = mysqli_query($this->link, $sql);
        //提取結果集存放到數組中
        if ($result && mysqli_affected_rows($this->link)) {
            while ($data = mysqli_fetch_assoc($result)) {
                $newData[] = $data;
            }
        }
        //返回結果集
        return $newData;
    }

    /**
     * exec
     *
     * @param [type] $sql
     * @param boolean $isInsert
     * @return void
     */
    function exec($sql, $isInsert = false)
    {
        //清空option數組中的值
        $this->initOptions();
        //執行sql語句
        $result = mysqli_query($this->link, $sql);
        if ($result && mysqli_affected_rows($this->link)) {
            //判斷是否是插入語句,根據不同的語句返回不同的結果
            if ($isInsert) {
                return mysqli_insert_id($this->link);
            } else {
                return mysqli_affected_rows($this->link);
            }
        }
        return false;
    }

    function __get($name)
    {
        if ($name == 'sql') {
            return $this->sql;
        }
        return false;
    }

    /**
     * insert函數
     * insert into 表名(字段) value(值)
     *
     * @param [type] $data  關聯數組,鍵就是字段名,值是字段值
     * @return void
     */
    function insert($data)
    {
        //處理值是字符串問題,兩邊需要添加單或雙引號
        $data = $this->parseValue($data);
        //提取所有的鍵,即就是所有的字段
        $keys = array_keys($data);
        //提取所有的值
        $values = array_values($data);
        //增加數據的sql語句
        $sql = 'insert into %TABLE%(%FIELD%) values(%VALUES%)';
        $sql = str_replace(['%TABLE%', '%FIELD%', '%VALUES%'], [$this->options['table'], join(',', $keys), join(',', $values)], $sql);
        $this->sql = $sql;
        return $this->exec($sql, true);
    }

    /**
     * 傳遞進來一個數組,將數組中值為字符串的兩邊加上引號
     *
     * @param [type] $data
     * @return void
     */
    protected function parseValue($data)
    {
        //遍歷數組,判斷是否為字符串,若是字符串,將其兩邊添加引號
        foreach ($data as $key => $value) {
            if (is_string($value)) {
                $value = '"' . $value . '"';
            }
            $newData[$key] = $value;
        }
        //返回處理后的數組
        return $newData;
    }

    /**
     * 刪除函數
     *
     * @return void
     */
    function delete()
    {
        //拼接sql語句
        $sql = 'delete from %TABLE% %WHERE%';
        $sql = str_replace(['%TABLE%', '%WHERE%'], [$this->options['table'], $this->options['where']], $sql);
        //保存sql語句
        $this->sql = $sql;
        //執行sql語句
        return $this->exec($sql);
    }

    /**
     * 更新函數
     * update 表名 set 字段名=字段值,字段名=字段值 where
     *
     * @param [type] $data
     * @return void
     */
    function update($data)
    {
        //處理$data數組中值為字符串加引號的問題
        $data = $this->parseValue($data);
        //將關聯數組拼接為固定的格式  鍵=值,鍵=值
        $value = $this->parseUpdate($data);
        //准備sql語句
        $sql = 'update %TABLE% set %VALUE% %WHERE%';
        $sql = str_replace(['%TABLE%', '%VALUE%', '%WHERE%'], [$this->options['table'], $value, $this->options['where']], $sql);
        //保存sql語句
        $this->sql = $sql;
        //執行sql語句
        return $this->exec($sql);
    }

    /**
     * 將關聯數組拼接為固定的格式
     *
     * @param [type] $data
     * @return void
     */
    protected function parseUpdate($data)
    {
        foreach ($data as $key => $value) {
            $newData[] = $key . '=' . $value;
        }
        return join(',', $newData);
    }

    /**
     * max函數
     *
     * @param [type] $field
     * @return void
     */
    function max($field)
    {
        //通過調用自己封裝的方法進行查詢
        $result = $this->field('max(' . $field . ') as max')->select();
        //select方法返回的是一個二維數組
        return $result[0]['max'];
    }

    /**
     * 析構方法
     */
    function __destruct()
    {
        mysqli_close($this->link);
    }

    /**
     * getByName   getByAge
     *
     * @param [type] $name
     * @param [type] $args
     * @return void
     */
    function __call($name, $args)
    {
        //獲取前5個字符
        $str = substr($name, 0, 5);
        //獲取后面的字段名
        $field = strtolower(substr($name, 5));
        //判斷前五個字符是否是getby
        if ($str === 'getBy') {
            return $this->where($field . '="' . $args[0] . '"')->select();
        }
        return false;
    }
}

confing數據庫配置文件,confing.php

<?php
return [
    'DB_HOST'=>'localhost',
    'DB_USER'=>'root',
    'DB_PWD'=>'123456',
    'DB_NAME'=>'test',
    'DB_CHARSET'=>'utf8',
    'DB_PREFIX'=>'t_',
];

 

 

<?php

$config = include 'config.php'; //引入數據庫配置文件
$model = new Model( $config);
//測試案例
// $saveData=['username'=>'張三','mobile'=>12334123];
// echo $model->table('user')->insert($saveData);
// var_dump($model->table('user')->where('id=5')->delete());
// var_dump($model->table('user')->limit('0,6')->field('username,mobile')->where('id>1')->order('id desc')->select());
// $updateData=['username'=>'張三'];
// var_dump($model->table('user')->where('id=3')->update($updateData));
// var_dump($model->table('user')->max('mobile'));
// var_dump($model->table('user')->getByUserName('張三'));
// var_dump($model->sql);

class Model
{
//主機名
protected $host;
//用戶名
protected $user;
//密碼
protected $pwd;
//數據庫名
protected $dbname;
//字符集
protected $charset;
//數據庫前綴
protected $prefix;

//數據庫連接資源
protected $link;
//數據表名 這里可以自己指定表名
protected $tableName;

//sql語句
protected $sql;
//操作數組 存放的就是所有的查詢條件
protected $options;

/**
* 構造方法,對成員變量進行初始化
*
* @param [type] $config
*/
function __construct( $config)
{
//對成員變量一一進行初始化
$this-> host = $config[ 'DB_HOST'];
$this-> user = $config[ 'DB_USER'];
$this-> pwd = $config[ 'DB_PWD'];
$this-> dbname = $config[ 'DB_NAME'];
$this-> charset = $config[ 'DB_CHARSET'];
$this-> prefix = $config[ 'DB_PREFIX'];

//連接數據庫
$this-> link = $this-> connect();

//得到數據表名 user===>UserModel
$this-> tableName = $this-> getTableName();

//初始化option數組
$this-> initOptions();
}

/**
* 連接數據庫
*
* @return void
*/
protected function connect()
{
$link = mysqli_connect( $this-> host, $this-> user, $this-> pwd);
if (! $link) {
die( '數據庫連接失敗');
}
//選擇數據庫
mysqli_select_db( $link, $this-> dbname);
//設置字符集
mysqli_set_charset( $link, $this-> charset);
//返回連接成功的資源
return $link;
}

/**
* 得到數據表名
*
* @return void
*/
protected function getTableName()
{
//第一種,如果設置了成員變量,那么通過成員變量來得到表名
if (! empty( $this-> tableName)) {
return $this-> prefix . $this-> tableName;
}
//第二種,如果沒有設置成員變量,那么通過類名來得到表名
//得到當前類名字符串
$className = get_class( $this);
//user UserModel goods GoodsModel
$table = strtolower( substr( $className, 0, - 5));
return $this-> prefix . $table;
}

/**
* 初始化option數組
*
* @return void
*/
protected function initOptions()
{
$arr = [ 'where', 'table', 'field', 'order', 'group', 'having', 'limit'];
foreach ( $arr as $value) {
//將options數組中這些鍵對應的值全部清空
$this-> options[ $value] = '';
if ( $value === 'table') {
$this-> options[ $value] = $this-> tableName;
} elseif ( $value == 'field') {
$this-> options[ $value] = '*';
}
}
}

/**
* field方法
*
* @param [type] $field
* @return void
*/
function field( $field)
{
//如果不為空,再進行處理
if (! empty( $field)) {
if ( is_string( $field)) {
$this-> options[ 'field'] = $field;
} elseif ( is_array( $field)) {
$this-> options[ 'field'] = join( ',', $field);
}
}
return $this;
}

/**
* //table方法
*
* @param [type] $table
* @return void
*/
function table( $table)
{
if (! empty( $table)) {
$this-> options[ 'table'] = $this-> prefix . $table;
}
return $this;
}

/**
* where方法
*
* @param [type] $where
* @return void
*/
function where( $where)
{
if (! empty( $where)) {
$this-> options[ 'where'] = 'where ' . $where;
}
return $this;
}

/**
* group方法
*
* @param [type] $group
* @return void
*/
function group( $group)
{
if (! empty( $group)) {
$this-> options[ 'group'] = 'group by ' . $group;
}
return $this;
}

/**
* having方法
*
* @param [type] $having
* @return void
*/
function having( $having)
{
if (! empty( $having)) {
$this-> options[ 'having'] = 'having ' . $having;
}
return $this;
}

/**
* order方法
*
* @param [type] $order
* @return void
*/
function order( $order)
{
if (! empty( $order)) {
$this-> options[ 'order'] = 'order by ' . $order;
}
return $this;
}

/**
* limit方法
*
* @param [type] $limit
* @return void
*/
function limit( $limit)
{
if (! empty( $limit)) {
if ( is_string( $limit)) {
$this-> options[ 'limit'] = 'limit ' . $limit;
} elseif ( is_array( $limit)) {
$this-> options[ 'limit'] = 'limit ' . join( ',', $limit);
}
}
return $this;
}

/**
* select方法
*
* @return void
*/
function select()
{
//先預寫一個帶占位符的sql語句
$sql = 'select %FIELD% from %TABLE% %WHERE% %GROUP% %HAVING% %ORDER% %LIMIT%';
//將options中對應的值依次的替換上面的占位符
$sql = str_replace(
[ '%FIELD%', '%TABLE%', '%WHERE%', '%GROUP%', '%HAVING%', '%ORDER%', '%LIMIT%'],
[
$this-> options[ 'field'], $this-> options[ 'table'], $this-> options[ 'where'], $this-> options[ 'group'],
$this-> options[ 'having'], $this-> options[ 'order'], $this-> options[ 'limit']
],
$sql
);
//保存一份sql語句
$this-> sql = $sql;
//執行sql語句
return $this-> query( $sql);
}

/**
* query
*
* @param [type] $sql
* @return void
*/
function query( $sql)
{
//清空option數組中的值
$this-> initOptions();
//執行sql語句
$result = mysqli_query( $this-> link, $sql);
//提取結果集存放到數組中
if ( $result && mysqli_affected_rows( $this-> link)) {
while ( $data = mysqli_fetch_assoc( $result)) {
$newData[] = $data;
}
}
//返回結果集
return $newData;
}

/**
* exec
*
* @param [type] $sql
* @param boolean $isInsert
* @return void
*/
function exec( $sql, $isInsert = false)
{
//清空option數組中的值
$this-> initOptions();
//執行sql語句
$result = mysqli_query( $this-> link, $sql);
if ( $result && mysqli_affected_rows( $this-> link)) {
//判斷是否是插入語句,根據不同的語句返回不同的結果
if ( $isInsert) {
return mysqli_insert_id( $this-> link);
} else {
return mysqli_affected_rows( $this-> link);
}
}
return false;
}

function __get( $name)
{
if ( $name == 'sql') {
return $this-> sql;
}
return false;
}

/**
* insert函數
* insert into 表名(字段) value(值)
*
* @param [type] $data 關聯數組,鍵就是字段名,值是字段值
* @return void
*/
function insert( $data)
{
//處理值是字符串問題,兩邊需要添加單或雙引號
$data = $this-> parseValue( $data);
//提取所有的鍵,即就是所有的字段
$keys = array_keys( $data);
//提取所有的值
$values = array_values( $data);
//增加數據的sql語句
$sql = 'insert into %TABLE%(%FIELD%) values(%VALUES%)';
$sql = str_replace([ '%TABLE%', '%FIELD%', '%VALUES%'], [ $this-> options[ 'table'], join( ',', $keys), join( ',', $values)], $sql);
$this-> sql = $sql;
return $this-> exec( $sql, true);
}

/**
* 傳遞進來一個數組,將數組中值為字符串的兩邊加上引號
*
* @param [type] $data
* @return void
*/
protected function parseValue( $data)
{
//遍歷數組,判斷是否為字符串,若是字符串,將其兩邊添加引號
foreach ( $data as $key => $value) {
if ( is_string( $value)) {
$value = '"' . $value . '"';
}
$newData[ $key] = $value;
}
//返回處理后的數組
return $newData;
}

/**
* 刪除函數
*
* @return void
*/
function delete()
{
//拼接sql語句
$sql = 'delete from %TABLE% %WHERE%';
$sql = str_replace([ '%TABLE%', '%WHERE%'], [ $this-> options[ 'table'], $this-> options[ 'where']], $sql);
//保存sql語句
$this-> sql = $sql;
//執行sql語句
return $this-> exec( $sql);
}

/**
* 更新函數
* update 表名 set 字段名=字段值,字段名=字段值 where
*
* @param [type] $data
* @return void
*/
function update( $data)
{
//處理$data數組中值為字符串加引號的問題
$data = $this-> parseValue( $data);
//將關聯數組拼接為固定的格式 鍵=值,鍵=值
$value = $this-> parseUpdate( $data);
//准備sql語句
$sql = 'update %TABLE% set %VALUE% %WHERE%';
$sql = str_replace([ '%TABLE%', '%VALUE%', '%WHERE%'], [ $this-> options[ 'table'], $value, $this-> options[ 'where']], $sql);
//保存sql語句
$this-> sql = $sql;
//執行sql語句
return $this-> exec( $sql);
}

/**
* 將關聯數組拼接為固定的格式
*
* @param [type] $data
* @return void
*/
protected function parseUpdate( $data)
{
foreach ( $data as $key => $value) {
$newData[] = $key . '=' . $value;
}
return join( ',', $newData);
}

/**
* max函數
*
* @param [type] $field
* @return void
*/
function max( $field)
{
//通過調用自己封裝的方法進行查詢
$result = $this-> field( 'max(' . $field . ') as max')-> select();
//select方法返回的是一個二維數組
return $result[ 0][ 'max'];
}

/**
* 析構方法
*/
function __destruct()
{
mysqli_close( $this-> link);
}

/**
* getByName getByAge
*
* @param [type] $name
* @param [type] $args
* @return void
*/
function __call( $name, $args)
{
//獲取前5個字符
$str = substr( $name, 0, 5);
//獲取后面的字段名
$field = strtolower( substr( $name, 5));
//判斷前五個字符是否是getby
if ( $str === 'getBy') {
return $this-> where( $field . '="' . $args[ 0] . '"')-> select();
}
return false;
}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM