Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
1 | <?php |
||
19 | class Request |
||
20 | { |
||
21 | /** |
||
22 | * @var string |
||
23 | */ |
||
24 | protected $method; |
||
25 | |||
26 | /** |
||
27 | * @var array |
||
28 | */ |
||
29 | protected $get; |
||
30 | |||
31 | /** |
||
32 | * @var array |
||
33 | */ |
||
34 | protected $post; |
||
35 | |||
36 | /** |
||
37 | * @var array |
||
38 | */ |
||
39 | protected $server; |
||
40 | |||
41 | /** |
||
42 | * @var array |
||
43 | */ |
||
44 | protected $cookie; |
||
45 | |||
46 | /** |
||
47 | * @var array |
||
48 | */ |
||
49 | protected $headers; |
||
50 | |||
51 | /** |
||
52 | * @var string |
||
53 | */ |
||
54 | protected $uri = '/'; |
||
55 | |||
56 | /** |
||
57 | * @param string $method |
||
58 | * @param array $get |
||
59 | * @param array $post |
||
60 | * @param array $server |
||
61 | * @param array $cookie |
||
62 | * @param array $headers |
||
63 | */ |
||
64 | 28 | public function __construct( |
|
87 | |||
88 | 1 | public static function createFromGlobals() |
|
100 | |||
101 | /** |
||
102 | * @return string |
||
103 | */ |
||
104 | 19 | public function getMethod() |
|
108 | |||
109 | /** |
||
110 | * @return string |
||
111 | */ |
||
112 | 17 | public function getUri() |
|
116 | |||
117 | /** |
||
118 | * @param string $source |
||
119 | * @param string $key |
||
120 | * @param mixed $default |
||
121 | */ |
||
122 | 28 | public function get($source, $key, $default = false) |
|
134 | |||
135 | /** |
||
136 | * @param string $key |
||
137 | * |
||
138 | * @return string |
||
139 | */ |
||
140 | 9 | View Code Duplication | public function getHeader($key) |
147 | |||
148 | /** |
||
149 | * @param string $key |
||
150 | * @param string $value |
||
151 | */ |
||
152 | 5 | public function addHeader($key, $value) |
|
156 | |||
157 | /** |
||
158 | * @param string $key |
||
159 | * |
||
160 | * @return string |
||
161 | */ |
||
162 | 9 | protected function normalizeHeaderName($key) |
|
166 | } |
||
167 |
Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable: