-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathAdapter.class.php
executable file
·84 lines (75 loc) · 1.9 KB
/
Adapter.class.php
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
<?php
/**
* 适配器模式, 主要使用适配器来更新接口,而不需要去改动公共接口的标准。
* 解决问题:在转换一个对象的接口用于另一个对象时,实现Adapter对象不仅是最佳做法,而且也能减少很多麻烦
*/
class errorObject
{
private $__error;
public function __construct($error)
{
$this->__error = $error;
}
public function getError()
{
return $this->__error;
}
}
//原需求
class logToConsole
{
private $__errorObject;
public function __construct($errorObject)
{
$this->__errorObject = $errorObject;
}
public function write()
{
fwrite(STDERR, $this->__errorObject->getError());
}
}
//新需求改变了
class logToCSV
{
const CSV_LOCATION = "log.csv";
private $__errorObject;
public function __construct($errorObject)
{
$this->__errorObject = $errorObject;
}
public function write()
{
$line = $this->__errorObject->getErrorNumber();
$line .= ",";
$line .= $this->__errorObject->getErrorText();
$line .= "\n";
file_put_contents(self::CSV_LOCATION, $line, FILE_APPEND);
}
}
//增加适配器,保持公共接口的标准性
class logToCsvAdapter extends errorObject
{
private $__errorNumber, $__errorText;
public function __construct($error)
{
parent::__construct($error);
$parts = explode(":", $this->getError());
$this->__errorNumber = $parts[0];
$this->__errorText = $parts[1];
}
public function getErrorNumber()
{
return $this->__errorNumber;
}
public function getErrorText()
{
return $this->__errorText;
}
}
//$error = new errorObject("404:Not Found");
//$log = new logToConsole($error);
//使用适配器来更新接口
$error = new logToCsvAdapter("404:Not Found");
$log = logToCSV($error);
$log->write();
?>