Home php教程 php手册 A simple ORM class

A simple ORM class

Dec 01, 2016 am 12:00 AM

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 of this Website
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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Digital audio output interface on the motherboard-SPDIF OUT Digital audio output interface on the motherboard-SPDIF OUT Jan 14, 2024 pm 04:42 PM

SPDIFOUT connection line sequence on the motherboard. Recently, I encountered a problem regarding the wiring sequence of the wires. I checked online. Some information says that 1, 2, and 4 correspond to out, +5V, and ground; while other information says that 1, 2, and 4 correspond to out, ground, and +5V. The best way is to check your motherboard manual. If you can't find the manual, you can use a multimeter to measure it. Find the ground first, then you can determine the order of the rest of the wiring. How to connect motherboard VDG wiring When connecting the VDG wiring of the motherboard, you need to plug one end of the VGA cable into the VGA interface of the monitor and the other end into the VGA interface of the computer's graphics card. Please be careful not to plug it into the motherboard's VGA port. Once connected, you can

Top 10 global digital currency trading apps recommended (2025 currency trading software ranking) Top 10 global digital currency trading apps recommended (2025 currency trading software ranking) Mar 12, 2025 pm 05:48 PM

This article recommends the top ten digital currency trading apps in the world, including Binance, OKX, Huobi Global, Coinbase, Kraken, Gate.io, KuCoin, Bitfinex, Gemini and Bitstamp. These platforms have their own characteristics in terms of transaction pair quantity, transaction speed, security, compliance, user experience, etc. For example, Binance is known for its high transaction speed and extensive services, while Coinbase is more suitable for novices. Choosing a platform that suits you requires comprehensive consideration of your own needs and risk tolerance. Learn about the world's mainstream digital currency trading platforms to help you conduct digital asset trading safely and efficiently.

How to install and register the btc trading app? How to install and register the btc trading app? Feb 21, 2025 pm 07:09 PM

This article will provide a detailed introduction to how to install and register a Bitcoin trading application. The Bitcoin trading app allows users to manage and trade cryptocurrencies such as Bitcoin. The article guides users through the installation and registration process step by step, including downloading applications, creating accounts, performing identity verification, and first deposit. The goal of the article is to provide beginners with clear and easy-to-understand guidelines to help them easily enter the world of Bitcoin trading.

Which digital currency app trading software is the best? Digital currency trading software big spot Which digital currency app trading software is the best? Digital currency trading software big spot Mar 07, 2025 pm 06:45 PM

There is no single "best" digital currency trading app, and the choice depends on personal needs. 1. OKX has powerful functions and rich currency types; 2. Binance has high liquidity and diverse transaction types; 3. Gate.io provides unique functions such as staking mining; 4. Huobi Global has a friendly interface and multi-language support; 5. Kraken focuses on security; 6. Coinbase is suitable for beginners and focuses on user education. When choosing, you need to consider security, liquidity, handling fees, functions, user experience and other factors.

Top 10 virtual digital currency trading platforms 2025 rankings, top ten virtual currency app exchanges Top 10 virtual digital currency trading platforms 2025 rankings, top ten virtual currency app exchanges Feb 21, 2025 pm 09:03 PM

This article introduces 10 mainstream cryptocurrency exchanges, covering basic information such as their establishment time, service scope, security, liquidity, transaction fees, etc. These exchanges include: OKX, Binance, Gate.io, Bitget, Coinbase, Huobi, KuCoin, Crypto.com, Gemini and Kraken.

Ouyi Exchange Download Official Portal Ouyi Exchange Download Official Portal Feb 21, 2025 pm 07:51 PM

Ouyi, also known as OKX, is a world-leading cryptocurrency trading platform. The article provides a download portal for Ouyi's official installation package, which facilitates users to install Ouyi client on different devices. This installation package supports Windows, Mac, Android and iOS systems. Users can choose the corresponding version to download according to their device type. After the installation is completed, users can register or log in to the Ouyi account, start trading cryptocurrencies and enjoy other services provided by the platform.

Digital currency trading platform 2025 Digital currency trading platform 2025 Mar 04, 2025 pm 07:06 PM

Based on global information, this article compiles the rankings of the world's leading virtual digital currency trading platforms, including Binance, OKX, Gate.io, Huobi, Coinbase, Kraken, Crypto.com, bitget, KuCoin and Bitstamp. These platforms have their own characteristics in terms of user count, transaction volume, transaction types, security, compliance, etc. For example, Binance is known for its large user base and extensive trading options, while Coinbase is known for its leadership and ease of use in the US market. Choosing a suitable trading platform requires weighing factors such as security, fees, and trading products based on your own needs.

What is Ouyi Exchange? What is the use of Ouyi Exchange? What is Ouyi Exchange? What is the use of Ouyi Exchange? Feb 15, 2025 pm 08:57 PM

Ouyi Exchange, formerly known as Binance, is one of the world's leading cryptocurrency trading platforms. It was founded in 2017 by Zhao Changpeng and is headquartered in Hong Kong, China. Ouyi Exchange provides users with a wide range of cryptocurrency trading services, including spot trading, futures trading, over-the-counter trading and crypto asset management.

See all articles