php 实现简单的 ORM(对象关系映射)
用php做开发很多年了,都没能真正的转到面向对象的开发模式,最近几年搞asp.net开发,说实话也都没能真正的转到面向对象。
网上很多关于面相过程与面相对象的讨论,个人觉得,不管是面向对象也好面向过程也罢只要能完美的解决问题就可以了。
怎么才能完美的解决问题呢?从需求出发,用最快最简单的方法去实现它。
这里的快包含,开发与效率的两个“快”。而简单,就是代码的简洁明了。
能够满足这两个条件了,还奢求什么。
不过,今天间看到php 关于 ORM(对象关系映射) 的文章,发现很像c#中的linq。
想想知识总归是要学习的,所以就用php做了个非常简单的实现ORM的demo。
废话不多说,直接看代码吧。
ABORM类
class ABORM { public $dbdriver = null; public $table = null; public $where = null; public $limit = null; public $sql = null; //public public function __construct(){ try { $this->dbdriver = new PDO("mysql:dbname=abshu3;host=127.0.0.1", "root", ""); $this->dbdriver->exec("SET NAMES 'utf8'"); } catch(PDOException $e){ echo('Error Connecting to DB: '+$e); } } public function __destruct(){ $this->dbdriver = null; } public function find($parm=null){ if($parm!=null){ $this->where = " WHERE ".$parm; }else{ $this->where = null; } $this->limit = null; return $this; } public function get_one($p = "*"){ $this->sql = "SELECT ".$p." FROM ".$this->table.$this->where.$this->limit; try{ $rs = $this->dbdriver->query( $this->sql ); $rs->setFetchMode(PDO::FETCH_ASSOC); $result_arr = $rs->fetch(); if($result_arr!=null) { if($p == "*"){ foreach($result_arr AS $k=>$v){ $this->$k = $v; } return $this; }else{ return $result_arr[$p]; } }else{ return null; } }catch(PDOException $e){ return null; } } public function get_all($p = "*"){ $a = array(); try{ $this->sql = "SELECT ".$p." FROM ".$this->table.$this->where.$this->limit; $rs = $this->dbdriver->query( $this->sql ); $rs->setFetchMode(PDO::FETCH_ASSOC); $result_arr = $rs->fetchAll(); foreach($result_arr AS $k=>$v){ $a[] = $v; } return $a; }catch(PDOException $e){ return null; } } }
news实体
class news extends ABORM{ public $id; public $title; public function __construct(){ $this->table = "news"; parent::__construct(); } public function __call($action, $parm){ $test = $this->$action( $parm ); return $this; } }
调用
$news = new news(); $one = $news->find("id=12")->get_one(); echo $one->id." ".$one->title."<br><br>"; $all = $news->find()->get_all(); foreach($all AS $v){ echo $v['id']." ".$v['title']."<br>"; }
运行效果
最后我个人觉得,简单快速就是美。
php本来就是一个简单快速的开发语言,何必搞的那么复杂呢。