php-orm-test 类似ORM的demo

做的一个类似ORM的demo,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
//基类
class ORM {

function __construct(){
echo "初始化ORM\n\n";
}

//保存信息
function save(){
//利用反射机制该类的属性赋值
$class=new ReflectionClass(get_class($this));
$object=$class->newInstanceArgs();
$properties=$class->getProperties();
foreach($properties as $property) {
$name=$property->getName();
$object->$name=$this->$name;
}
//var_dump($object);
echo "调用REST接口\n\n";
}

//读取信息
function init(){
echo "在init,调用REST接口\n\n";
$objName=get_class($this);
switch($objName){
case 'Member':
$dataFromAPI=array('memberId'=>1,'name'=>'gangzi','phone'=>'13312345678');
break;
case 'MemberGrade':
$dataFromAPI=array('id'=>1,'grade'=>99);
break;
}
$class=new ReflectionClass($objName);
$properties=$class->getProperties();
foreach($properties as $property) {
$name=$property->getName();
if(isset($this->$name))
$this->$name=$dataFromAPI[$name];
}
}

function __destruct(){
}

function error(){
}
}

//会员类
class Member extends ORM{
var $memberId=0;
var $name='';
var $phone='';
var $gradeHandle=null;

function __construct($phone=''){
echo "初始化Member\n\n";
$this->init();
//初始化会员等级
$this->gradeHandle=new MemberGrade($this->memberId);
}
}

//会员等级类
class MemberGrade extends ORM{
var $id;
var $grade;

function __construct($id=0){
parent::__construct();
}

function __set($name, $val){
if($this->$name=='grade') return Dictionary::getGrade((int)$val);
$this->$name=$val;
}

function __get($name)
{

return isset($this->$name) ? $this->$name : null;
}
}

//字典类
class Dictionary{
function __construct(){}
static function getGrade($val){
//读取API信息
return 2;
}
}

echo "<pre>";
//调用过程
$phone='12345678901';
$memberInfo=array('id'=>2,'name'=>'gangzi','phone'=>$phone,);
$oM=new Member($phone);
$oM->gradeHandle->grade=Dictionary::getGrade(100);
$oM->gradeHandle->save();
var_dump($oM);