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 | * Used by beforeSave() to ensure child classes call parent::beforeSave(). |
||
| 14 | * |
||
| 15 | * @var bool |
||
| 16 | */ |
||
| 17 | protected $brokenBeforeSave = false; |
||
| 18 | |||
| 19 | /** |
||
| 20 | * Used by afterSave() to ensure child classes call parent::afterSave(). |
||
| 21 | * |
||
| 22 | * @var bool |
||
| 23 | */ |
||
| 24 | protected $brokenAfterSave = false; |
||
| 25 | |||
| 26 | /** |
||
| 27 | * Relations to Update during Save and |
||
| 28 | * the appropriate method to fire the update with. |
||
| 29 | * |
||
| 30 | * @var array |
||
| 31 | */ |
||
| 32 | protected $doSaveRelations = ['BelongsTo' => 'associate']; |
||
| 33 | |||
| 34 | /** |
||
| 35 | * Relations to Update after Save and |
||
| 36 | * the appropriate method to fire the update with. |
||
| 37 | * |
||
| 38 | * @var array |
||
| 39 | */ |
||
| 40 | protected $afterSaveRelations = ['BelongsToMany' => 'sync']; |
||
| 41 | |||
| 42 | /** |
||
| 43 | * Method fired before the Save action is undertaken. |
||
| 44 | * |
||
| 45 | * @return |
||
| 46 | */ |
||
| 47 | protected function beforeSave() |
||
| 53 | |||
| 54 | /** |
||
| 55 | * Save Action. |
||
| 56 | * |
||
| 57 | * Fires off beforeSave(), doSave() and afterSave() |
||
| 58 | * |
||
| 59 | * @return |
||
| 60 | */ |
||
| 61 | public function save() |
||
| 77 | |||
| 78 | /** |
||
| 79 | * The actual Save action, which does all of hte pre-processing |
||
| 80 | * required before we are able to perform the save() function. |
||
| 81 | * |
||
| 82 | * @return |
||
| 83 | */ |
||
| 84 | private function doSave() |
||
| 109 | |||
| 110 | /** |
||
| 111 | * Method fired after the Save action is complete. |
||
| 112 | * |
||
| 113 | * @return |
||
| 114 | */ |
||
| 115 | protected function afterSave() |
||
| 129 | |||
| 130 | /** |
||
| 131 | * Method fired to Save Relations. |
||
| 132 | * |
||
| 133 | * @param string $action The current action (either doSave or afterSave) |
||
| 134 | * @param string $key |
||
| 135 | * @param string $value |
||
| 136 | * |
||
| 137 | * @return |
||
| 138 | */ |
||
| 139 | private function saveRelation($action, $key, $value) |
||
| 152 | } |
||
| 153 |
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: