Home  >  Article  >  php教程  >  A simple ORM class

A simple ORM class

WBOY
WBOYOriginal
2016-12-01 00:00:211426browse

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