博客列表 >利用接口实现一个基本数据库的操作类(CURD)——2019年8月2日22时03分

利用接口实现一个基本数据库的操作类(CURD)——2019年8月2日22时03分

嘿哈的博客
嘿哈的博客原创
2019年08月06日 10:17:44853浏览

类的自动加载

str_replace() 字符串替换语法

sql_autoload_register( function(){} ) 自动加载函数

file_exists() 确定文件是否存在


抽象类与抽象方法:

abstract 抽象关键字;

抽象类不能实例化,类中抽象方法必须在子类全部实现;

abstract public function setName ($value); 抽象方法

在子类 创建public function setName($value); 实现父类的抽象方法

接口原理与实现

interface {} 定义一个接口;

implement 类实现接口的关键字

注意:

1.接口不能实例化;

2.接口中只允许出现抽象方法;

3.接口中成员必须是公共/public;

4.允许有常量;

5.实现接口的子类,必须将接口的抽象方法全部实现;


类的自动加载

class Loader
{
    public static function autoLoader()
    {
        sql_autoload_register(function($className){
            $path = str_replace('\\','/',$className);
            $path = __DIR__ . '/' . $path . 'php';
            if(file_exists($path)){
                require $path ; 
            }
        });
    }
}


实例

<?php

    namespace demo;

    //定义一个接口
    interface iCurd
    {
        //增加
        public function create($data);
        //查询
        public function read();
        //设置
        public function update($data,$where);
        //删除
        public function delete($where);

    }

    class sub implements iCurd
    {
        //连接对象
        protected $pdo=null;

        protected $table='staff';
        //连接数据库
        public function __construct($dsn,$username,$password,$table)
        {
            $this->pdo = new \PDO($dsn,$username,$password);
            $this->table = $table;
        }

        //增加方法
        public function create($data)
        {
            //字段
            $fields = ' (name,age,sex,position,mobile,hiredate) ';
            //值
            $values = ' (:name, :age, :sex, :position, :mobile, :hiredate) ';
            //sql语句
            $sql = 'INSERT INTO '.$this->table . $fields . ' VALUES ' . $values ;
            //sql预处理
            $stmt = $this->pdo->prepare($sql);
//            die($stmt->debugDumpParams());
            $stmt->execute($data);

            //返回新增数据
            return [
                'count' => $stmt->rowCount(),
                'id' => $this->pdo->lastInsertId()
            ];

        }
        //查询方法
        public function read($fields = '*',$where = '',$limit = '0, 5')
        {
            $where = empty($where) ? $where : ' WHERE '.$where;
            $limit = ' LIMIT '.$limit;
            $sql = 'SELECT '.$fields . ' FROM '.$this->table . $where . $limit;

            $stmt = $this->pdo->prepare($sql);
            $stmt -> execute();
//            die($stmt->debugDumpParams());
            return $stmt->fetchAll(\PDO::FETCH_ASSOC);
        }
        //更新方法
        public function update($data,$where)
        {
            // 获取$data的键值
            $keyArr = array_keys($data);
            $set = '';

            foreach ($keyArr as $value){
                $set .= $value .'= :'.$value.',';
            }
            //去除右边的逗号
            $set = rtrim($set,',');
            //sql语句
            $sql = 'UPDATE ' .$this->table .' SET '.$set.' WHERE '.$where;
            //预处理
            $stmt = $this->pdo->prepare($sql);
            $stmt->execute($data);
//            die($stmt->debugDumpParams());
            return $stmt->rowCount();
        }
        //删除方法
        public function delete($where)
        {
            $sql = 'DELETE FROM '.$this->table .' WHERE '. $where;
            $stmt = $this->pdo->prepare($sql);
            $stmt->execute();

            return $stmt->rowCount();
        }

    }

    //客户端代码
    //实例化数据库
    $dsn = 'mysql:host=127.0.0.1;dbname=php';
    $password = 'root';
    $username = 'root';
    $table = 'staff'; //表名
    $db = new sub($dsn,$username,$password,$table);

    //导入数据
    $data = [

        'name'=> '洪吉潮',
        'age'=> 18,
        'sex' => 1,
        'position' => '主席',
        'mobile'=> '15626475734',
        'hiredate' => time()

    ];
    //增加执行结果
//    $res = $db->create($data);
//    echo '成功新增 '. $res['count']. '条记录, 新增记录ID是: '. $res['id'];
//    echo '<hr>';

    //查询执行结果
    foreach ($db->read('name,age,position','staff_id>5','5')as $item ){
     print_r($item);
    echo '<br>';
    }
    echo '<hr>';
    //更新执行结果
    $data = [
        'name' => '李文茜'
    ];
    $where = 'staff_id=12';
    echo '成功更新'.$db->update($data,$where).'条记录';
    echo '<hr>';
    //删除执行结果
    $where = 'staff_id=11';
    echo '成功删除'.$db->delete($where).'条记录';

运行实例 »

点击 "运行实例" 按钮查看在线实例



声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议