-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdata_obj.php
More file actions
88 lines (73 loc) · 2.1 KB
/
data_obj.php
File metadata and controls
88 lines (73 loc) · 2.1 KB
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
<?php
//資料原型物件,強迫必須繼承且提供公用方法,讓繼承物件無法直接更改資料陣列
abstract class Data_Object{
private $data_array = array();
protected function __construct($data_pattern){
$this->data_array = $data_pattern;
}
final public function get($key = null){
if($key == null){
return $this->data_array;
}else{
if($this->key_exist($key)){
return $this->data_array[$key];
}
return null;
}
}
final public function batch_get(array $keys){
$result = array();
foreach ($keys as $key) {
if($this->key_exist($key)){
$result[$key] = $this->data_array[$key];
}
}
return $result;
}
final public function set(string $key, $value){
if($this->key_exist($key)){
$this->data_array[$key] = $value;
}
}
final public function batch_set(array $data){
foreach ($data as $key => $value) {
if($this->key_exist($key)){
$this->data_array[$key] = $value;
}
}
}
private function key_exist($key){
if(array_key_exists($key, $this->data_array)){
return true;
}
return false;
}
}
//實際的資料物件,用來定義資料模型及特有的方法
//除了持久化資料的類別,例如DB以外,不與其他類別互動
class Member_Data extends Data_Object{
public function __construct(){
$member_data = array( //資料模型與預設值
'id' => 1, //會員編號
'name' => 'Maro', //會員名稱
'create' => '2014-01-10', //建立日期
);
parent::__construct($member_data); //定義資料模型
}
public function load_from_db(){
//從DB讀取之類的
}
}
//資料操作物件,與其他類別互動
class Member_Handle{
public function __construct(){
$member_data = new Member_Data();
$this->dothing($member_data);
}
public function dothing(Member_Data $member_data){ //強制傳入處理函式的參數型別,以確定資料模型正確
$member_data->batch_set(array('id' => 2, 'name' => 'Test', 'test' => 'fake')); //故意嘗試更新一個不存在的鍵
var_dump($member_data->get()); //輸出的結果將會保有原來資料模型的架構
}
}
$demo = new Member_Handle();
?>