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 |
||
25 | class TargetUpsell extends Upsell |
||
26 | { |
||
27 | /** |
||
28 | * @var Cart |
||
29 | */ |
||
30 | protected $_cart; |
||
31 | /** |
||
32 | * @var Config |
||
33 | */ |
||
34 | protected $_config; |
||
35 | /** |
||
36 | * @var UpsellModel |
||
37 | */ |
||
38 | protected $_upsell; |
||
39 | /** |
||
40 | * @var Manager |
||
41 | */ |
||
42 | protected $_moduleManager; |
||
43 | |||
44 | /** |
||
45 | * @param Context $context |
||
46 | * @param Index $index |
||
47 | * @param Data $targetRuleData |
||
48 | * @param CollectionFactory $productCollectionFactory |
||
49 | * @param Visibility $visibility |
||
50 | * @param IndexFactory $indexFactory |
||
51 | * @param Cart $cart |
||
52 | * @param Config $config |
||
53 | * @param UpsellModel $upsell |
||
54 | * @param Manager $moduleManager |
||
55 | */ |
||
56 | View Code Duplication | public function __construct( |
|
82 | |||
83 | /** |
||
84 | * Rewrite parent getAllItems method to use PredictionIO results when available |
||
85 | * Rewrites the target rules for Enterprise edition |
||
86 | * |
||
87 | * @return array |
||
88 | */ |
||
89 | public function getAllItems() |
||
117 | } |
||
118 |
Let’s assume that you have a directory layout like this:
and let’s assume the following content of
Bar.php
:If both files
OtherDir/Foo.php
andSomeDir/Foo.php
are loaded in the same runtime, you will see a PHP error such as the following:PHP Fatal error: Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php
However, as
OtherDir/Foo.php
does not necessarily have to be loaded and the error is only triggered if it is loaded beforeOtherDir/Bar.php
, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias: