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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153


/**
* 过滤接口
*/
interface FilterInterface
{
/**
* 过滤方法
*
* @param SportsMan $person 运动员
* @return mixed
*/
public function filter(array $person);
}


/**
* 按运动项目过滤实体
*/
class SportsPerson
{
/**
* 性别
* @var string
*/
private $_gender = '';

/**
* 按照本运动项目过滤
* @var string
*/
private $_sportType = '';

/**
* 构造函数
* @param string $gender
* @param string $sportType
*/
public function __construct($gender='', $sportType='')
{
$this->_gender = $gender;
$this->_sportType = $sportType;
}

/**
* 魔法函数
* @param string $value
* @return mixed
*/
public function __get($value='')
{
$value = '_' . $value;
return $this->$value;
}
}

/**
* 按性别过滤实体
*/
class FilterGender implements FilterInterface
{
/**
* 按照本性别过滤
* @var string
*/
private $_gender = '';

/**
* 构造函数
* @param string $gender
*/
public function __construct($gender='')
{
$this->_gender = $gender;
}

/**
* 过滤方法
*
* @param array $persons 运动员集合
* @return mixed
*/
public function filter(array $persons)
{
foreach ($persons as $k => $v) {
if ($v->gender === $this->_gender) {
$personsFilter[] = $persons[$k];
}
}
return $personsFilter;
}
}

/**
* 按运动项目过滤实体
*/
class FilterSportType implements FilterInterface
{
/**
* 按照本运动项目过滤
* @var string
*/
private $_sportType = '';

/**
* 构造函数
* @param string $sportType
*/
public function __construct($sportType='')
{
$this->_sportType = $sportType;
}

/**
* 过滤方法
*
* @param array $persons 运动员集合
* @return mixed
*/
public function filter(array $persons)
{
foreach ($persons as $k => $v) {
if ($v->sportType === $this->_sportType) {
$personsFilter[] = $persons[$k];
}
}
return $personsFilter;
}
}


try {
// 定义一组运动员
$persons = [];
echo '<pre/>';
$persons[] = new SportsPerson('male', 'basketball');
$persons[] = new SportsPerson('female', 'basketball');
$persons[] = new SportsPerson('male', 'football');
$persons[] = new SportsPerson('female', 'football');
$persons[] = new SportsPerson('male', 'swim');
$persons[] = new SportsPerson('female', 'swim');

// 按过滤男性
$filterGender = new FilterGender('male');
var_dump($filterGender->filter($persons));
// 过滤运动项目篮球
$filterSportType = new FilterSportType('basketball');
var_dump($filterSportType->filter($persons));

} catch (\Exception $e) {
echo $e->getMessage();
}