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 |
||
| 15 | class UserController extends Controller |
||
| 16 | { |
||
| 17 | /** |
||
| 18 | * Constructor |
||
| 19 | */ |
||
| 20 | public function __construct() |
||
| 21 | { |
||
| 22 | parent::__construct(); |
||
| 23 | |||
| 24 | $action = Route::getFacadeRoot()->current()->getActionMethod(); |
||
| 25 | |||
| 26 | if (in_array($action, ['index', 'show'])) { |
||
| 27 | $this->breadcrumbs->addCrumb('Users', route('users.user.index')); |
||
|
|
|||
| 28 | } |
||
| 29 | } |
||
| 30 | |||
| 31 | /** |
||
| 32 | * Show all the users. |
||
| 33 | * |
||
| 34 | * @return \Illuminate\View\View |
||
| 35 | */ |
||
| 36 | public function index(): View |
||
| 40 | |||
| 41 | /** |
||
| 42 | * Show the user profile page. |
||
| 43 | * |
||
| 44 | * @param string $slug The slug of the user. |
||
| 45 | * |
||
| 46 | * @return \Illuminate\Http\RedirectResponse|\Illuminate\View\View |
||
| 47 | */ |
||
| 48 | public function show(Request $request, string $slug) |
||
| 77 | |||
| 78 | /** |
||
| 79 | * Show the settings form. |
||
| 80 | * |
||
| 81 | * @return \Illuminate\View\View |
||
| 82 | */ |
||
| 83 | public function showSettingsForm(): View |
||
| 91 | |||
| 92 | /** |
||
| 93 | * Handle an update request for the user. |
||
| 94 | * |
||
| 95 | * @param \Illuminate\Http\Request $request |
||
| 96 | * |
||
| 97 | * @return \Illuminate\Http\RedirectResponse |
||
| 98 | */ |
||
| 99 | public function update(Request $request): RedirectResponse |
||
| 116 | |||
| 117 | /** |
||
| 118 | * Handle the delete request for the user. |
||
| 119 | * |
||
| 120 | * @param \Illuminate\Http\Request $request |
||
| 121 | * |
||
| 122 | * @return \Illuminate\Http\RedirectResponse |
||
| 123 | */ |
||
| 124 | View Code Duplication | public function delete(Request $request): RedirectResponse |
|
| 145 | |||
| 146 | /** |
||
| 147 | * Handle a E-mail update request for the user. |
||
| 148 | * |
||
| 149 | * @param \Illuminate\Http\Request $request |
||
| 150 | * |
||
| 151 | * @return \Illuminate\Http\RedirectResponse |
||
| 152 | */ |
||
| 153 | protected function updateEmail(Request $request): RedirectResponse |
||
| 162 | |||
| 163 | /** |
||
| 164 | * Handle a Password update request for the user. |
||
| 165 | * |
||
| 166 | * @param \Illuminate\Http\Request $request |
||
| 167 | * |
||
| 168 | * @return \Illuminate\Http\RedirectResponse |
||
| 169 | */ |
||
| 170 | protected function updatePassword(Request $request): RedirectResponse |
||
| 187 | } |
||
| 188 |
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: