一个简易的ORM类

陌涛大大_8069

陌涛大大_8069

2016-12-01

1654人浏览

原创

自己写的一个简易的ORM类,给感兴趣的朋友提供一点思路。
自己写的一个简易的ORM类,给感兴趣的朋友提供一点思路。借鉴了一点TP的思路。 /**
 * author: NickBai
 * createTime: 2016/11/28 0028 下午 4:00
 */
class MyOrm implements ArrayAccess
{
    public $host = '127.0.0.1';  //数据库地址
    public $dbname = 'test';   //数据库名
    public $user = 'root';  //数据库用户名
    public $pwd = 'root';   //数据库密码
    public $port = '3306';  //数据库端口
    public $charset = 'utf8';   //数据库编码
    private $conn = null;    //数据库链接资源
    private $alias = [];  //记录全局的语句参数
    private $sql;    //存储最后一条sql

    public function __construct()
    {
        if( is_null( $this->conn ) ){

            $dsn = "mysql:host=$this->host;dbname=$this->dbname;charset=$this->charset;port=$this->port";
            $this->conn = new PDO( $dsn, $this->user, $this->pwd );
        }
    }

    //field语句
    public function field( $field )
    {
        if( !is_string( $field ) ){
            throw new exception("field语句的参数必须为字符串");
        }

        $this->alias['field'] = $field;
        return $this;
    }

    //table语句
    public function table( $table )
    {
        if( !is_string( $table ) ){
            throw new exception("table语句的参数必须为字符串");
        }

        $this->alias['table'] = $table;
        return $this;
    }

    //where语句
    public function where( $where )
    {
        $this->alias['where'] = '';
        if( is_array( $where ) ){

            foreach( $where as $key=>$vo ){
                $this->alias['where'] .= " `$key`" . ' = ' . $vo . ' and ';
            }
            $this->alias['where'] = rtrim( $this->alias['where'], 'and ' );

        }else if( is_string( $where ) ){

            $this->alias['where'] = $where;
        }else{

            throw new exception("where语句的参数必须为数组或字符串");
        }

        return $this;
    }

    //limit语句
    public function limit( $limit )
    {
        $this->alias['limit'] = '';
        if( is_numeric( $limit ) ){
           $this->alias['limit'] = '0,' . $limit;
        }else if( is_string( $limit ) ){
            $this->alias['limit'] = $limit;
        }else{
            throw new exception("limit语句的参数必须为数字或字符串");
        }

        return $this;
    }

    //order语句
    public function order( $order )
    {
        if( !is_string( $order ) ){
            throw new exception("order语句的参数必须为字符串");
        }

        $this->alias['order'] = $order;
        return $this;
    }

    //group语句
    public function group( $group )
    {
        if( !is_string( $group ) ){
            throw new exception("group语句的参数必须为字符串");
        }

        $this->alias['group'] = $group;
        return $this;
    }

    //解析查询sql语句
    public function ParseSelectSql()
    {
        $this->sql = 'select *';
        if( !empty( $this->alias['field'] ) ){
            $this->sql = str_replace( '*', $this->alias['field'], $this->sql );
        }

        if( empty( $this->alias['table'] ) ){
            throw new exception("请用table子句设置查询表");
        }else{

            $this->sql .= ' from ' . $this->alias['table'];
        }

        if( !empty( $this->alias['where'] ) ){
            $this->sql .= ' where ' . $this->alias['where'];
        }

        if( !empty( $this->alias['group'] ) ){
            $this->sql .= ' group by ' . $this->alias['group'];
        }

        if( !empty( $this->alias['order'] ) ){
            $this->sql .= ' order by ' . $this->alias['order'];
        }

        if( !empty( $this->alias['limit'] ) ){
            $this->sql .= ' limit ' . $this->alias['limit'];
        }

    }

    //解析添加sql语句
    public function ParseAddSql()
    {
        $this->sql = 'insert into ';
        if( empty( $this->alias['table'] ) ){
            throw new exception("请用table子句设置添加表");
        }else{

            $this->sql .= $this->alias['table'] . ' set ';
        }

        return $this->sql;
    }

    //解析更新sql语句
    public function ParseUpdateSql()
    {
        $this->sql = 'update ';
        if( empty( $this->alias['table'] ) ){
            throw new exception("请用table子句设置修改表");
        }else{

            $this->sql .= $this->alias['table'] . ' set ';
        }

        if( empty( $this->alias['where'] ) ){
            throw new exception("更新语句必须有where子句指定条件");
        }

        return $this->sql;
    }

    //解析删除sql语句
    public function ParseDeleteSql()
    {
        $this->sql = 'delete from ';
        if( empty( $this->alias['table'] ) ){
            throw new exception("请用table子句设置删除表");
        }else{

            $this->sql .= $this->alias['table'];
        }

        if( empty( $this->alias['where'] ) ){
            throw new exception("删除语句必须有where子句指定条件");
        }

        $this->sql .= ' where ' . $this->alias['where'];

        return $this->sql;
    }


    //查询语句
    public function select()
    {
        $this->ParseSelectSql();
        $row = $this->conn->query( $this->sql )->fetchAll( PDO::FETCH_ASSOC );
        $result = [];

        foreach( $row as $key=>$vo ){

            $arrObj = clone $this;  //clone当前对象防止对this对象造成污染
            $arrObj->data = $vo;
            $result[$key] = $arrObj;
            unset( $arrObj );
        }

        return $result;
    }

    //查询一条
    public function find()
    {
        $this->ParseSelectSql();
        $row = $this->conn->query( $this->sql )->fetch( PDO::FETCH_ASSOC );

        $arrObj = clone $this;  //clone当前对象防止对this对象造成污染
        $arrObj->data = $row;
        $result = $arrObj;
        unset( $arrObj );

        return $result;
    }

    //添加数据
    public function add( $data )
    {
        if( !is_array( $data ) ){
            throw new exception("添加数据add方法参数必须为数组");
        }

        $this->ParseAddSql();
        foreach( $data as $key=>$vo ){
            $this->sql .= " `{$key}` = '" . $vo . "',";
        }

        $this->conn->exec( rtrim( $this->sql, ',' ) );
        return $this->conn->lastInsertId();
    }

    //更新语句
    public function update( $data )
    {
        if( !is_array( $data ) ){
            throw new exception("更新数据update方法参数必须为数组");
        }

        $this->ParseUpdateSql();
        foreach( $data as $key=>$vo ){
            $this->sql .= " `{$key}` = '" . $vo . "',";
        }

        $this->sql = rtrim( $this->sql, ',' ) . ' where ' . $this->alias['where'];
        return $this->conn->exec( $this->sql );

    }

    //删除语句
    public function delete()
    {
        $this->ParseDeleteSql();
        return $this->conn->exec( $this->sql );
    }

    //获取查询数据
    public function getData()
    {
        return $this->data;
    }

    //获取最后一次执行的sql语句
    public function getLastSql()
    {
        return $this->sql;
    }

    public function __get($name)
    {
        return $this->getData()[$name];
    }

    public function offsetExists($offset)
    {
        if( !isset( $this->getData()[$offset] ) ){
            return NULL;
        }
    }

    public function offsetGet($offset)
    {
        return $this->getData()[$offset];
    }

    public function offsetSet($offset, $value)
    {
        return $this->data[$offset] = $value;
    }

    public function offsetUnset($offset)
    {
        unset( $this->data[$offset] );
    }
}
你可以这么用:$orm = new MyOrm();

//查询语句
$res = $orm->table('user')->order('id desc')->select();
$res = $orm->table('user')->where("name='test'")->order('id desc')->select();
$res = $orm->table('user')->where(['id' => 1])->order('id desc')->find();
$res = $orm->table('user')->where("age > 20")->group('group by name')->order('id desc')->limit(2)->select();
$res = $orm->table('user')->where("age > 20")->group('group by name')->order('id desc')->limit('2,2')->select();

//你可以这样处理数据
foreach( $res as $key=>$vo ){
    echo $vo->name . '
';
}
//也可以这样处理
foreach( $res as $key=>$vo ){
    echo $vo['name'] . '
';
}
//还可以这样
foreach( $res as $key=>$vo ){
    print_r( $vo->getData() ) . '
';
}

//添加数据
$data = [
    'name' => 'test1',
    'age' => 20,
    'password' => '21232f297a57a5a743894a0e4a801fc3',
    'salt' => 'domain'
];
$res = $orm->table('user')->add( $data );

//更新数据
$res = $orm->table('user')->where(['id' => 4])->update( ['name' => 'sdfdsfdsd', 'salt' => '111'] );

//删除数据
$res = $orm->table('user')->where(['id' => 7, 'id' => 6])->delete();

//获取执行的sql语句
echo $orm->getLastSql();

var_dump($res);

相关文章

PHP速学视频免费教程(入门到精通)
PHP速学视频免费教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载

相关标签:

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

相关专题

更多
GoFrame框架Web开发与路由中间件
GoFrame框架Web开发与路由中间件

本专题聚焦GoFrame框架的Web开发,拆解路由注册与匹配规则、请求参数获取、参数校验与中间件执行顺序,说明统一响应、JWT鉴权、文件上传与接口文档生成的落地方式,并补充优雅重启与测试实践。

2026.11.17

0

15

GoFrame框架安装与gf命令行工具
GoFrame框架安装与gf命令行工具

本专题围绕GoFrame框架的安装与工具链配置展开,讲清Go版本要求、gf命令行的安装方式、代理镜像与依赖准备,说明项目初始化、热编译、交叉编译打包的做法,并整理安装阶段的常见报错与验证步骤。

2026.11.17

0

15

GoFrame框架零基础入门
GoFrame框架零基础入门

本专题整理GoFrame框架的入门知识,从模块化设计理念、环境准备到跑通第一个Web服务,讲清目录分层、配置加载、日志与中间件的用法,并对比Gin、Go-Zero的差异,帮助Go开发者建立整体认知。

2026.11.17

0

15

SQLAlchemy 一对多关系怎么建立
SQLAlchemy 一对多关系怎么建立

SQLAlchemy 一对多关系怎么建立?本专题整理父子表外键、relationship 双向映射、关联查询、级联删除和加载优化等相关文章,帮助你理解并实现常见的 ORM 关系建模。

2026.11.17

0

10

SQLAlchemy 如何增删改查
SQLAlchemy 如何增删改查

SQLAlchemy 如何增删改查?本专题整理 ORM 新增记录、条件查询、更新和删除、Session 事务提交与批量处理等实用文章,帮助你掌握 Python 数据库操作流程。

2026.11.17

0

11

SQLAlchemy ORM 模型怎么写
SQLAlchemy ORM 模型怎么写

SQLAlchemy ORM 模型怎么写?本专题整理模型类定义、Mapped 字段映射、主键与约束、表结构创建和常见报错的相关文章,帮助你从基础配置到实际建模逐步掌握 SQLAlchemy。

2026.11.17

0

16

Go-Zero API开发使用教程
Go-Zero API开发使用教程

本专题聚焦Go-Zero的API开发,拆解.api描述文件的语法结构、路由与分组定义、参数绑定与校验规则,说明统一响应体、JWT鉴权、跨域与接口文档生成的落地方式,并给出网关聚合与接口测试的实践建议。

2026.11.12

160

15

Go-Zero安装与goctl环境配置教程
Go-Zero安装与goctl环境配置教程

本专题围绕Go-Zero的安装与工具链配置展开,讲清Go版本要求、goctl安装方式、代理镜像、protoc依赖与环境变量设置,说明多版本共存、升级回退与CI流水线安装的做法,并整理安装阶段的常见报错与验证步骤。

2026.11.12

120

15

Go-Zero零基础入门教程
Go-Zero零基础入门教程

本专题整理Go-Zero的入门知识,从框架定位、环境准备到跑通第一个API服务,讲清目录分层、配置加载、日志与中间件的基本用法,并对比Gin、Kratos的差异,帮助Go开发者建立整体认知,判断它是否适合当前项目。

2026.11.12

100

15

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
动力学院设计模式PHP视频教程
动力学院设计模式PHP视频教程

共15课时 | 3.5万人学习

Node.js基础教程
Node.js基础教程

共8课时 | 1.5万人学习

Node.js,就该这样学
Node.js,就该这样学

共27课时 | 3.9万人学习