php教程 php手册 一个简易的ORM类

一个简易的ORM类

Dec 01, 2016 am 12:00 AM

自己写的一个简易的ORM类,给感兴趣的朋友提供一点思路。
自己写的一个简易的ORM类,给感兴趣的朋友提供一点思路。借鉴了一点TP的思路。<?php <br /> /**<br>  * author: NickBai<br>  * createTime: 2016/11/28 0028 下午 4:00<br>  */<br> class MyOrm implements ArrayAccess<br> {<br>     public $host = '127.0.0.1';  //数据库地址<br>     public $dbname = 'test';   //数据库名<br>     public $user = 'root';  //数据库用户名<br>     public $pwd = 'root';   //数据库密码<br>     public $port = '3306';  //数据库端口<br>     public $charset = 'utf8';   //数据库编码<br>     private $conn = null;    //数据库链接资源<br>     private $alias = [];  //记录全局的语句参数<br>     private $sql;    //存储最后一条sql<br> <br>     public function __construct()<br>     {<br>         if( is_null( $this->conn ) ){<br> <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语句<br>     public function field( $field )<br>     {<br>         if( !is_string( $field ) ){<br>             throw new exception("field语句的参数必须为字符串");<br>         }<br> <br>         $this->alias['field'] = $field;<br>         return $this;<br>     }<br> <br>     //table语句<br>     public function table( $table )<br>     {<br>         if( !is_string( $table ) ){<br>             throw new exception("table语句的参数必须为字符串");<br>         }<br> <br>         $this->alias['table'] = $table;<br>         return $this;<br>     }<br> <br>     //where语句<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("where语句的参数必须为数组或字符串");<br>         }<br> <br>         return $this;<br>     }<br> <br>     //limit语句<br>     public function limit( $limit )<br>     {<br>         $this->alias['limit'] = '';<br>         if( is_numeric( $limit ) ){<br>            $this->alias['limit'] = '0,' . $limit;<br>         }else if( is_string( $limit ) ){<br>             $this->alias['limit'] = $limit;<br>         }else{<br>             throw new exception("limit语句的参数必须为数字或字符串");<br>         }<br> <br>         return $this;<br>     }<br> <br>     //order语句<br>     public function order( $order )<br>     {<br>         if( !is_string( $order ) ){<br>             throw new exception("order语句的参数必须为字符串");<br>         }<br> <br>         $this->alias['order'] = $order;<br>         return $this;<br>     }<br> <br>     //group语句<br>     public function group( $group )<br>     {<br>         if( !is_string( $group ) ){<br>             throw new exception("group语句的参数必须为字符串");<br>         }<br> <br>         $this->alias['group'] = $group;<br>         return $this;<br>     }<br> <br>     //解析查询sql语句<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->alias['table'] ) ){<br>             throw new exception("请用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当前对象防止对this对象造成污染<br>             $arrObj->data = $vo;<br>             $result[$key] = $arrObj;<br>             unset( $arrObj );<br>         }<br> <br>         return $result;<br>     }<br> <br>     //查询一条<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当前对象防止对this对象造成污染<br>         $arrObj->data = $row;<br>         $result = $arrObj;<br>         unset( $arrObj );<br> <br>         return $result;<br>     }<br> <br>     //添加数据<br>     public function add( $data )<br>     {<br>         if( !is_array( $data ) ){<br>             throw new exception("添加数据add方法参数必须为数组");<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>     //更新语句<br>     public function update( $data )<br>     {<br>         if( !is_array( $data ) ){<br>             throw new exception("更新数据update方法参数必须为数组");<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>     //删除语句<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);

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25 : Myrise에서 모든 것을 잠금 해제하는 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

마더보드의 디지털 오디오 출력 인터페이스 - SPDIF OUT 마더보드의 디지털 오디오 출력 인터페이스 - SPDIF OUT Jan 14, 2024 pm 04:42 PM

마더보드의 SPDIFOUT 연결 라인 순서 최근에 전선의 배선 순서에 문제가 발생했습니다. 온라인에서 확인해 보니 1, 2, 4가 out, +5V, ground에 해당한다는 정보도 있고, 1, 2, 4가 out, ground, +5V에 해당한다는 정보도 있습니다. 가장 좋은 방법은 마더보드 설명서를 확인하는 것입니다. 설명서를 찾을 수 없으면 멀티미터를 사용하여 측정할 수 있습니다. 먼저 접지를 찾은 다음 나머지 배선의 순서를 결정할 수 있습니다. 마더보드 VDG 배선 연결 방법 마더보드의 VDG 배선을 연결할 때 VGA 케이블의 한쪽 끝을 모니터의 VGA 인터페이스에 연결하고 다른 쪽 끝을 컴퓨터 그래픽 카드의 VGA 인터페이스에 연결해야 합니다. 마더보드의 VGA 포트에 연결하지 않도록 주의하세요. 연결되면 다음을 수행할 수 있습니다.

BTC Trading 앱을 설치하고 등록하는 방법은 무엇입니까? BTC Trading 앱을 설치하고 등록하는 방법은 무엇입니까? Feb 21, 2025 pm 07:09 PM

이 기사는 비트 코인 거래 응용 프로그램을 설치하고 등록하는 방법에 대한 자세한 소개를 제공합니다. 비트 코인 트레이딩 앱을 통해 사용자는 비트 코인과 같은 암호 화폐를 관리하고 거래 할 수 있습니다. 이 기사는 응용 프로그램 다운로드, 계정 작성, ID 검증 수행 및 첫 입금을 포함하여 설치 및 등록 프로세스를 단계별로 안내합니다. 이 기사의 목표는 초보자에게 명확하고 이해하기 쉬운 지침을 제공하여 비트 코인 거래 세계에 쉽게 들어가도록 도와줍니다.

Ouyi Exchange 다운로드 공식 포털 Ouyi Exchange 다운로드 공식 포털 Feb 21, 2025 pm 07:51 PM

OKX라고도하는 Ouyi는 세계 최고의 암호 화폐 거래 플랫폼입니다. 이 기사는 OUYI의 공식 설치 패키지 용 다운로드 포털을 제공하여 사용자가 다른 장치에 OUYI 클라이언트를 설치할 수 있도록합니다. 이 설치 패키지는 Windows, Mac, Android 및 iOS 시스템을 지원합니다. 설치가 완료되면 사용자는 OUYI 계정에 등록하거나 로그인하고 암호 화폐 거래를 시작하며 플랫폼에서 제공하는 기타 서비스를 즐길 수 있습니다.

상위 10 개 글로벌 디지털 통화 거래 앱 권장 (2025 통화 거래 소프트웨어 순위) 상위 10 개 글로벌 디지털 통화 거래 앱 권장 (2025 통화 거래 소프트웨어 순위) Mar 12, 2025 pm 05:48 PM

이 기사는 Binance, OKX, Huobi Global, Coinbase, Kraken, Gate.io, Kucoin, Bitfinex, Gemini 및 Bitstamp를 포함하여 세계 10 대 디지털 통화 거래 앱을 권장합니다. 이 플랫폼은 트랜잭션 쌍 수량, 트랜잭션 속도, 보안, 컴플라이언스, 사용자 경험 등의 측면에서 고유 한 특성을 가지고 있습니다. 예를 들어, Binance는 높은 트랜잭션 속도와 광범위한 서비스로 유명하지만 코인베이스는 초보자에게 더 적합합니다. 자신에게 적합한 플랫폼을 선택하려면 자신의 요구와 위험에 대한 포괄적 인 고려가 필요합니다. 디지털 자산 거래를 안전하고 효율적으로 수행하는 데 도움이되는 세계의 주류 디지털 통화 거래 플랫폼에 대해 알아보십시오.

어떤 디지털 통화 앱 거래 소프트웨어가 가장 좋습니까? 어떤 디지털 통화 앱 거래 소프트웨어가 가장 좋습니까? Mar 07, 2025 pm 06:45 PM

단일 "최고의"디지털 통화 거래 앱은 없으며 선택은 개인의 요구에 따라 다릅니다. 1. OKX는 강력한 기능과 풍부한 유동성을 가지고 있습니다. 선택할 때 보안, 유동성, 처리 비용, 기능, 사용자 경험 및 기타 요인을 고려해야합니다.

세 가지 주요 가상 통화 앱은 무엇입니까? 세 가지 주요 가상 통화 앱은 무엇입니까? Mar 04, 2025 pm 08:51 PM

가상 통화 시장은 급성장하고 있으며 많은 거래 플랫폼이 탄생합니다. 이 기사는 우수한 사용자 경험, 강력한 보안 및 풍부한 기능으로 알려진 가상 통화 필드의 세 가지 주요 응용 프로그램을 소개합니다. 이러한 응용 프로그램에는 Binance, Gate.io 및 Ouyi가 포함되어 있으며, 이는 투자자에게 가상 통화를 구매, 판매, 거래 및 추적하는 편리하고 안전한 방법을 제공합니다.

상위 10 개의 가상 디지털 통화 거래 플랫폼 2025 순위, 상위 10 개 가상 통화 앱 교환 상위 10 개의 가상 디지털 통화 거래 플랫폼 2025 순위, 상위 10 개 가상 통화 앱 교환 Feb 21, 2025 pm 09:03 PM

이 기사는 설립 시간, 서비스 범위, 보안, 유동성, 거래 수수료 등과 같은 기본 정보를 다루는 10 가지 주류 cryptocurrency 거래소를 소개합니다. 이러한 교환에는 OKX, Binance, Gate.io, Bitget, Coinbase, Huobi, Kucoin, Crypto.com, Gemini 및 Kraken이 포함됩니다.

디지털 통화 거래 플랫폼 2025 디지털 통화 거래 플랫폼 2025 Mar 04, 2025 pm 07:06 PM

글로벌 정보를 기반 으로이 기사는 Binance, OKX, Gate.io, Huobi, Coinbase, Kraken, Crypto.com, Bitget, Kucoin 및 Bitstamp를 포함한 세계 최고의 가상 디지털 통화 거래 플랫폼의 순위를 컴파일합니다. 이 플랫폼은 사용자 수, 거래량, 거래 유형, 보안, 규정 준수 등의 특성을 가지고 있습니다. 예를 들어, Binance는 대규모 사용자 기반 및 광범위한 거래 옵션으로 유명하며 Coinbase는 미국 시장에서 리더십과 사용 편의성으로 유명합니다. 적절한 거래 플랫폼을 선택하려면 보안, 수수료 및 자신의 요구에 따라 거래 제품과 같은 계량 요소가 필요합니다.

See all articles