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 |
||
14 | class DefaultController extends Controller |
||
15 | { |
||
16 | /** |
||
17 | * {@inheritdoc} |
||
18 | */ |
||
19 | View Code Duplication | public function behaviors() |
|
|
|||
20 | { |
||
21 | return [ |
||
22 | 'access' => [ |
||
23 | 'class' => AccessControl::className(), |
||
24 | 'rules' => [ |
||
25 | [ |
||
26 | 'allow' => true, |
||
27 | 'actions' => ['error'], |
||
28 | ], |
||
29 | [ |
||
30 | 'allow' => true, |
||
31 | 'matchCallback' => function ($rule, $action) { |
||
32 | return \Yii::$app->user->can( |
||
33 | $this->module->id.'_'.$this->id.'_'.$action->id, |
||
34 | ['route' => true] |
||
35 | ); |
||
36 | }, |
||
37 | ], |
||
38 | ], |
||
39 | ], |
||
40 | ]; |
||
41 | } |
||
42 | |||
43 | /** |
||
44 | * Actions defined in classes, eg. error page. |
||
45 | * |
||
46 | * @return array |
||
47 | */ |
||
48 | public function actions() |
||
49 | { |
||
50 | return [ |
||
51 | 'error' => [ |
||
52 | 'class' => 'yii\web\ErrorAction', |
||
53 | ], |
||
54 | ]; |
||
55 | } |
||
56 | |||
57 | /** |
||
58 | * Application dashboard. |
||
59 | * |
||
60 | * @return string |
||
61 | */ |
||
62 | public function actionIndex() |
||
66 | |||
67 | /** |
||
68 | * Application configuration. |
||
69 | * |
||
70 | * @return string |
||
71 | */ |
||
72 | public function actionViewConfig() |
||
92 | } |
||
93 |
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.