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 |
||
8 | trait ManagedModelTrait |
||
9 | { |
||
10 | /** |
||
11 | * @var RepositoryManager Repository manager. |
||
12 | */ |
||
13 | protected $_manager; |
||
14 | |||
15 | /** |
||
16 | * @var array Registered references. |
||
17 | */ |
||
18 | protected $_references; |
||
19 | |||
20 | |||
21 | /** |
||
22 | * Inject a reference to repository manager. |
||
23 | * |
||
24 | * @param RepositoryManager $manager Repository manager. |
||
25 | * |
||
26 | * @return self |
||
27 | */ |
||
28 | 10 | public function setManager($manager) |
|
33 | |||
34 | |||
35 | /** |
||
36 | * Return registered foreign model references. |
||
37 | * |
||
38 | * @return array Array of references. |
||
39 | */ |
||
40 | 6 | public function getReferences() |
|
44 | |||
45 | |||
46 | /** |
||
47 | * Register foreign model references. |
||
48 | * |
||
49 | * @param array $references Array of references (name => config). |
||
50 | * |
||
51 | * @return self |
||
52 | */ |
||
53 | 12 | public function setReferences($references) |
|
64 | |||
65 | |||
66 | /** |
||
67 | * Retrieve a reference by name. |
||
68 | * |
||
69 | * @param string $name Reference name. |
||
70 | * |
||
71 | * @return mixed Model instance if found, null otherwise. |
||
72 | * |
||
73 | * @throws RepositoryException If this model or the referenced model is not handled by a managed repository. |
||
74 | */ |
||
75 | 5 | View Code Duplication | public function getReference($name) |
90 | |||
91 | |||
92 | /** |
||
93 | * Retrieve a reference by direct attribute access. |
||
94 | * |
||
95 | * @param string $attr Attribute name. |
||
96 | * |
||
97 | * @throws RepositoryException If the requested attribute does not resolve to a registered magic reference. |
||
98 | */ |
||
99 | 7 | public function __get($attr) |
|
108 | } |
||
109 |
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.