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 |
||
8 | final class Manager |
||
9 | { |
||
10 | /** |
||
11 | * @var Connector |
||
12 | */ |
||
13 | private $connector; |
||
14 | |||
15 | /** |
||
16 | * @var Builder |
||
17 | */ |
||
18 | private $builder; |
||
19 | |||
20 | /** |
||
21 | * @var array |
||
22 | */ |
||
23 | private $operations = []; |
||
24 | |||
25 | /** |
||
26 | * @param Connector $connector |
||
27 | * @param Builder $builder |
||
28 | */ |
||
29 | 2 | public function __construct(Connector $connector, Builder $builder) |
|
34 | |||
35 | /** |
||
36 | * @param string $method |
||
37 | * @param array $parameters |
||
38 | * |
||
39 | * @return mixed |
||
40 | */ |
||
41 | 2 | public function __call($method, array $parameters = []) |
|
48 | |||
49 | /** |
||
50 | * @param string $key |
||
51 | * @param mixed $value |
||
52 | * |
||
53 | * @return static |
||
54 | */ |
||
55 | 2 | public function cloneWith($key, $value) |
|
62 | |||
63 | /** |
||
64 | * @param string $table |
||
65 | * |
||
66 | * @return static |
||
67 | */ |
||
68 | 2 | public function table($table) |
|
72 | |||
73 | /** |
||
74 | * @param string $columns |
||
75 | * |
||
76 | * @return static |
||
77 | */ |
||
78 | 2 | public function select($columns = "*") |
|
82 | |||
83 | /** |
||
84 | * @return PromiseInterface |
||
85 | */ |
||
86 | 2 | public function first() |
|
93 | |||
94 | /** |
||
95 | * @return PromiseInterface |
||
96 | */ |
||
97 | 2 | public function get() |
|
106 | |||
107 | /** |
||
108 | * @param Builder $builder |
||
109 | * |
||
110 | * @return Builder |
||
111 | */ |
||
112 | 2 | private function applyOperationsTo($builder) |
|
121 | |||
122 | /** |
||
123 | * @param array $data |
||
124 | * |
||
125 | * @return PromiseInterface |
||
126 | */ |
||
127 | 2 | View Code Duplication | public function insert(array $data) |
137 | |||
138 | /** |
||
139 | * @param array $data |
||
140 | * |
||
141 | * @return PromiseInterface |
||
142 | */ |
||
143 | View Code Duplication | public function update(array $data) |
|
153 | |||
154 | /** |
||
155 | * @return PromiseInterface |
||
156 | */ |
||
157 | View Code Duplication | public function delete() |
|
167 | } |
||
168 |
If you implement
__call
and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.This is often the case, when
__call
is implemented by a parent class and only the child class knows which methods exist: