search
Homephp教程php手册A simple ORM class

I wrote a simple ORM class myself to provide some ideas for interested friends.
I wrote a simple ORM class by myself to provide some ideas for interested friends. I borrowed a little bit of TP’s ideas. <?php <br /> /**<br> * author: NickBai<br> *createTime: 2016/11/28 0028 4:00 pm<br> ​*/<br> class MyOrm implements ArrayAccess<br> {<br> Public $host = '127.0.0.1'; //Database address<br> Public $dbname = 'test'; //Database name<br> Public $user = 'root'; //Database user name<br> Public $pwd = 'root'; //Database password<br> Public $port = '3306'; //Database port<br> Public $charset = 'utf8'; //Database encoding<br> Private $ conn = null; // Database link resources <br> Private $alias = []; //Record global statement parameters<br>        private $sql;      // Store the last sql<br> <br> Public function __construct()<br> {<br>                                                                                                                                                                                                                                                                                                        if( <br>                 $dsn = "mysql:host=$this->host;dbname=$this->dbname;charset=$this->charset;port=$this->port";<br>               $this->conn = new PDO( $dsn, $this->user, $this->pwd);<br>         }<br> }<br> <br> //Field statement<br> Public function field($field)<br> {<br> If (! Is_string ($ field)) {<br> ​​​​​​throw new exception("The parameters of the field statement must be strings");<br>         }<br> <br>           $this->alias['field'] = $field;<br> Return $ this; <br> }<br> <br> //table statement<br> Public function table($table)<br> {<br>                                                                                                                                                                                                                                                                                                        if( ​​​​​​throw new exception("The parameters of the table statement must be strings");<br>         }<br> <br>           $this->alias['table'] = $table;<br> Return $ this; <br> }<br> <br> //where statement<br> Public function where($where)<br> {<br>          $this->alias['where'] = '';<br> ​​​​​if(​is_array(​$where)​){<br> <br> foreach( $where as $key=>$vo ){<br>                   $this->alias['where'] .= " `$key`" . ' = ' . $vo . ' and ';<br>              }<br>                 $this->alias['where'] = rtrim( $this->alias['where'], 'and ' );<br> <br>         }else if(  is_string(  $where  )){<br> <br>                $this->alias['where'] = $where;<br>            }else{<br> <br>​​​​​​throw new exception("The parameters of the where statement must be an array or a string");<br>         }<br> <br> Return $ this; <br> }<br> <br> //limit statement<br> Public function limit($limit)<br> {<br>          $this->alias['limit'] = '';<br>             if(                                                                                                                 $this->alias['limit'] = '0,' . $limit;<br>         }else if(  is_string(  $limit  )){<br>                $this->alias['limit'] = $limit;<br>            }else{<br> ​​​​​​throw new exception("The parameters of the limit statement must be numbers or strings");<br>         }<br> <br> Return $ this; <br> }<br> <br> //Order statement<br> Public function order( $order)<br> {<br>                                                                                                                                                                                                                                                                                                      if( ​​​​​​throw new exception("The parameters of the order statement must be strings");<br>         }<br> <br>           $this->alias['order'] = $order;<br> Return $ this; <br> }<br> <br> //group statement<br> Public function group($group)<br> {<br> If (! Is_string ($ Group)) {<br> ​​​​​​throw new exception("The parameter of the group statement must be a string");<br>         }<br> <br>           $this->alias['group'] = $group;<br> Return $ this; <br> }<br> <br> //Parse query sql statement<br> Public function ParseSelectSql()<br> {<br>          $this->sql = 'select *';<br> If( !empty( $this->alias['field'] ) ){<br>                $this->sql = str_replace( '*', $this->alias['field'], $this->sql );<br>         }<br> <br> If (Empty ($ this- & gt; alias ['table'])) {<br> ​​​​​​throw new exception("Please use the table clause to set the query table");<br>            }else{<br> <br> $this->sql .= ' from ' . $this->alias['table'];<br>         }<br> <br> If( !empty( $this->alias['where'] ) ){<br> $this->sql .= ' where ' . $this->alias['where'];<br>         }<br> <br> If( !empty( $this->alias['group'] ) ){<br> $this->sql .= ' group by ' . $this->alias['group'];<br>        }<br> <br>         if( !empty( $this->alias['order'] ) ){<br>             $this->sql .= ' order by ' . $this->alias['order'];<br>         }<br> <br>         if( !empty( $this->alias['limit'] ) ){<br>             $this->sql .= ' limit ' . $this->alias['limit'];<br>         }<br> <br>     }<br> <br>     //解析添加sql语句<br>     public function ParseAddSql()<br>     {<br>         $this->sql = 'insert into ';<br>         if( empty( $this->alias['table'] ) ){<br>             throw new exception("请用table子句设置添加表");<br>         }else{<br> <br>             $this->sql .= $this->alias['table'] . ' set ';<br>         }<br> <br>         return $this->sql;<br>     }<br> <br>     //解析更新sql语句<br>     public function ParseUpdateSql()<br>     {<br>         $this->sql = 'update ';<br>         if( empty( $this->alias['table'] ) ){<br>             throw new exception("请用table子句设置修改表");<br>         }else{<br> <br>             $this->sql .= $this->alias['table'] . ' set ';<br>         }<br> <br>         if( empty( $this->alias['where'] ) ){<br>             throw new exception("更新语句必须有where子句指定条件");<br>         }<br> <br>         return $this->sql;<br>     }<br> <br>     //解析删除sql语句<br>     public function ParseDeleteSql()<br>     {<br>         $this->sql = 'delete from ';<br>         if( empty( $this->alias['table'] ) ){<br>             throw new exception("请用table子句设置删除表");<br>         }else{<br> <br>             $this->sql .= $this->alias['table'];<br>         }<br> <br>         if( empty( $this->alias['where'] ) ){<br>             throw new exception("删除语句必须有where子句指定条件");<br>         }<br> <br>         $this->sql .= ' where ' . $this->alias['where'];<br> <br>         return $this->sql;<br>     }<br> <br> <br>     //查询语句<br>     public function select()<br>     {<br>         $this->ParseSelectSql();<br>         $row = $this->conn->query( $this->sql )->fetchAll( PDO::FETCH_ASSOC );<br>          $result = [];<br> <br> foreach( $row as $key=>$vo ){<br> <br>              $arrObj = clone $this; //Clone the current object to prevent contamination of this object<br>                 $arrObj->data = $vo;<br>               $result[$key] = $arrObj;<br> ​​​​​​unset($arrObj);<br>         }<br> <br> Return $ result; <br> }<br> <br> //Query one item<br> Public function find()<br> {<br>           $this->ParseSelectSql();<br>          $row = $this->conn->query( $this->sql )->fetch( PDO::FETCH_ASSOC );<br> <br>          $arrObj = clone $this; //Clone the current object to prevent contamination of this object<br>          $arrObj->data = $row;<br>         $result = $arrObj;<br> ​​​​unset($arrObj);<br> <br> Return $ result; <br> }<br> <br> //Add data<br> Public function add($data)<br> {<br>                                                                                                                                                                                                                                                                                                        if( ​​​​​​throw new exception("Add data add method parameters must be arrays");<br>         }<br> <br>          $this->ParseAddSql();<br> foreach( $data as $key=>$vo ){<br>                 $this->sql .= " `{$key}` = '" . $vo . "',";<br>         }<br> <br>            $this->conn->exec( rtrim( $this->sql, ',' ));<br>            return $this->conn->lastInsertId();<br> }<br> <br> //Update statement<br> Public function update($data)<br> {<br>                                                                                                                                                                                                                                                                                                        if( ​​​​​​throw new exception("Update data update method parameters must be arrays");<br>         }<br> <br>           $this->ParseUpdateSql();<br> foreach( $data as $key=>$vo ){<br>                 $this->sql .= " `{$key}` = '" . $vo . "',";<br>         }<br> <br>            $this->sql = rtrim( $this->sql, ',') . ' where ' . $this->alias['where'];<br>            return $this->conn->exec( $this->sql );<br> <br> }<br> <br> //Delete statement<br> Public function delete()<br> {<br>          $this->ParseDeleteSql();<br>            return $this->conn->exec( $this->sql );<br>    }<br> <br>     //获取查询数据<br>     public function getData()<br>     {<br>         return $this->data;<br>     }<br> <br>     //获取最后一次执行的sql语句<br>     public function getLastSql()<br>     {<br>         return $this->sql;<br>     }<br> <br>     public function __get($name)<br>     {<br>         return $this->getData()[$name];<br>     }<br> <br>     public function offsetExists($offset)<br>     {<br>         if( !isset( $this->getData()[$offset] ) ){<br>             return NULL;<br>         }<br>     }<br> <br>     public function offsetGet($offset)<br>     {<br>         return $this->getData()[$offset];<br>     }<br> <br>     public function offsetSet($offset, $value)<br>     {<br>         return $this->data[$offset] = $value;<br>     }<br> <br>     public function offsetUnset($offset)<br>     {<br>         unset( $this->data[$offset] );<br>     }<br> }你可以这么用:$orm = new MyOrm();<br> <br> //查询语句<br> $res = $orm->table('user')->order('id desc')->select();<br> $res = $orm->table('user')->where("name='test'")->order('id desc')->select();<br> $res = $orm->table('user')->where(['id' => 1])->order('id desc')->find();<br> $res = $orm->table('user')->where("age > 20")->group('group by name')->order('id desc')->limit(2)->select();<br> $res = $orm->table('user')->where("age > 20")->group('group by name')->order('id desc')->limit('2,2')->select();<br> <br> //你可以这样处理数据<br> foreach( $res as $key=>$vo ){<br>     echo $vo->name . '<br>';<br> }<br> //也可以这样处理<br> foreach( $res as $key=>$vo ){<br>     echo $vo['name'] . '<br>';<br> }<br> //还可以这样<br> foreach( $res as $key=>$vo ){<br>     print_r( $vo->getData() ) . '<br>';<br> }<br> <br> //添加数据<br> $data = [<br>     'name' => 'test1',<br>     'age' => 20,<br>     'password' => '21232f297a57a5a743894a0e4a801fc3',<br>     'salt' => 'domain'<br> ];<br> $res = $orm->table('user')->add( $data );<br> <br> //更新数据<br> $res = $orm->table('user')->where(['id' => 4])->update( ['name' => 'sdfdsfdsd', 'salt' => '111'] );<br> <br> //删除数据<br> $res = $orm->table('user')->where(['id' => 7, 'id' => 6])->delete();<br> <br> //获取执行的sql语句<br> echo $orm->getLastSql();<br> <br> var_dump($res);

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment