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 |
||
9 | trait ModelSaving |
||
10 | { |
||
11 | /** |
||
12 | * Relations to Update during Save and |
||
13 | * the appropriate method to fire the update with. |
||
14 | * |
||
15 | * @var array |
||
16 | */ |
||
17 | protected $doSaveRelations = ['BelongsTo' => 'associate']; |
||
18 | |||
19 | /** |
||
20 | * Relations to Update after Save and |
||
21 | * the appropriate method to fire the update with. |
||
22 | * |
||
23 | * @var array |
||
24 | */ |
||
25 | protected $afterSaveRelations = ['BelongsToMany' => 'sync']; |
||
26 | |||
27 | /** |
||
28 | * Method fired before the Save action is undertaken. |
||
29 | * |
||
30 | * @return |
||
31 | */ |
||
32 | protected function beforeSave() |
||
35 | |||
36 | /** |
||
37 | * Save Action. |
||
38 | * |
||
39 | * Fires off beforeSave(), doSave() and afterSave() |
||
40 | * |
||
41 | * @return |
||
42 | */ |
||
43 | public function save() |
||
55 | |||
56 | /** |
||
57 | * The actual Save action, which does all of hte pre-processing |
||
58 | * required before we are able to perform the save() function. |
||
59 | * |
||
60 | * @return |
||
61 | */ |
||
62 | private function doSave() |
||
83 | |||
84 | /** |
||
85 | * Method fired after the Save action is complete. |
||
86 | * |
||
87 | * @return |
||
88 | */ |
||
89 | protected function afterSave() |
||
101 | |||
102 | /** |
||
103 | * Method fired to Save Relations. |
||
104 | * |
||
105 | * @param string $action The current action (either doSave or afterSave) |
||
106 | * @param string $key |
||
107 | * @param string $value |
||
108 | * |
||
109 | * @return |
||
110 | */ |
||
111 | private function saveRelation($action, $key, $value) |
||
124 | } |
||
125 |