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 |
||
| 10 | trait ModelSaving |
||
| 11 | { |
||
| 12 | /** |
||
| 13 | * Relations to Update during Save and |
||
| 14 | * the appropriate method to fire the update with. |
||
| 15 | * |
||
| 16 | * @var array |
||
| 17 | */ |
||
| 18 | protected $doSaveRelations = ['BelongsTo' => 'associate']; |
||
| 19 | |||
| 20 | /** |
||
| 21 | * Relations to Update after Save and |
||
| 22 | * the appropriate method to fire the update with. |
||
| 23 | * |
||
| 24 | * @var array |
||
| 25 | */ |
||
| 26 | protected $afterSaveRelations = ['BelongsToMany' => 'sync']; |
||
| 27 | |||
| 28 | /** |
||
| 29 | * Method fired before the Save action is undertaken. |
||
| 30 | * |
||
| 31 | * @return |
||
| 32 | */ |
||
| 33 | protected function beforeSave() |
||
| 36 | |||
| 37 | /** |
||
| 38 | * Save Action. |
||
| 39 | * |
||
| 40 | * Fires off beforeSave(), doSave() and afterSave() |
||
| 41 | * |
||
| 42 | * @return |
||
| 43 | */ |
||
| 44 | public function save() |
||
| 56 | |||
| 57 | /** |
||
| 58 | * The actual Save action, which does all of hte pre-processing |
||
| 59 | * required before we are able to perform the save() function. |
||
| 60 | * |
||
| 61 | * @return |
||
| 62 | */ |
||
| 63 | private function doSave() |
||
| 84 | |||
| 85 | /** |
||
| 86 | * Method fired after the Save action is complete. |
||
| 87 | * |
||
| 88 | * @return |
||
| 89 | */ |
||
| 90 | protected function afterSave() |
||
| 103 | |||
| 104 | /** |
||
| 105 | * Method fired to Save Relations. |
||
| 106 | * |
||
| 107 | * @param string $action The current action (either doSave or afterSave) |
||
| 108 | * @param string $key |
||
| 109 | * @param string $value |
||
| 110 | * |
||
| 111 | * @return |
||
| 112 | */ |
||
| 113 | private function saveRelation($action, $key, $value) |
||
| 126 | } |
||
| 127 |
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: