0

0

一个简易的ORM类

php中文网

php中文网

发布时间:2016-12-01 00:00:21

|

1594人浏览过

|

来源于php中文网

原创

自己写的一个简易的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);

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

相关专题

更多
Java 桌面应用开发(JavaFX 实战)
Java 桌面应用开发(JavaFX 实战)

本专题系统讲解 Java 在桌面应用开发领域的实战应用,重点围绕 JavaFX 框架,涵盖界面布局、控件使用、事件处理、FXML、样式美化(CSS)、多线程与UI响应优化,以及桌面应用的打包与发布。通过完整示例项目,帮助学习者掌握 使用 Java 构建现代化、跨平台桌面应用程序的核心能力。

37

2026.01.14

php与html混编教程大全
php与html混编教程大全

本专题整合了php和html混编相关教程,阅读专题下面的文章了解更多详细内容。

19

2026.01.13

PHP 高性能
PHP 高性能

本专题整合了PHP高性能相关教程大全,阅读专题下面的文章了解更多详细内容。

37

2026.01.13

MySQL数据库报错常见问题及解决方法大全
MySQL数据库报错常见问题及解决方法大全

本专题整合了MySQL数据库报错常见问题及解决方法,阅读专题下面的文章了解更多详细内容。

19

2026.01.13

PHP 文件上传
PHP 文件上传

本专题整合了PHP实现文件上传相关教程,阅读专题下面的文章了解更多详细内容。

16

2026.01.13

PHP缓存策略教程大全
PHP缓存策略教程大全

本专题整合了PHP缓存相关教程,阅读专题下面的文章了解更多详细内容。

6

2026.01.13

jQuery 正则表达式相关教程
jQuery 正则表达式相关教程

本专题整合了jQuery正则表达式相关教程大全,阅读专题下面的文章了解更多详细内容。

3

2026.01.13

交互式图表和动态图表教程汇总
交互式图表和动态图表教程汇总

本专题整合了交互式图表和动态图表的相关内容,阅读专题下面的文章了解更多详细内容。

45

2026.01.13

nginx配置文件详细教程
nginx配置文件详细教程

本专题整合了nginx配置文件相关教程详细汇总,阅读专题下面的文章了解更多详细内容。

9

2026.01.13

热门下载

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

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
Git 教程
Git 教程

共21课时 | 2.7万人学习

Kotlin 教程
Kotlin 教程

共23课时 | 2.5万人学习

PHP新手语法线上课程教学
PHP新手语法线上课程教学

共13课时 | 0.9万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号