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 |
||
| 11 | View Code Duplication | class View2 |
|
| 12 | { |
||
| 13 | /** |
||
| 14 | * @var $template Template file or array |
||
| 15 | * @var $templateData Data to send to template file |
||
| 16 | * @var $sortOrder For sorting views |
||
| 17 | * @var $type Type of view |
||
| 18 | */ |
||
| 19 | private $template; |
||
| 20 | private $templateData = []; |
||
| 21 | private $sortOrder; |
||
| 22 | private $type; |
||
| 23 | |||
| 24 | |||
| 25 | |||
| 26 | /** |
||
| 27 | * Set values for the view. |
||
| 28 | * |
||
| 29 | * @param array|string $template the template file, or array |
||
| 30 | * @param array $data variables to make available to the |
||
| 31 | * view, default is empty |
||
| 32 | * @param integer $sort which order to display the views, |
||
| 33 | * if suitable |
||
| 34 | * @param string $type which type of view |
||
| 35 | * |
||
| 36 | * @return self |
||
| 37 | */ |
||
| 38 | public function set($template, $data = [], $sort = 0, $type = "file") |
||
| 70 | |||
| 71 | |||
| 72 | |||
| 73 | /** |
||
| 74 | * Render the view. |
||
| 75 | * |
||
| 76 | * @param object $di optional with access to the framework resources. |
||
| 77 | * |
||
| 78 | * @return void |
||
| 79 | */ |
||
| 80 | public function render($di = null) |
||
| 110 | |||
| 111 | |||
| 112 | |||
| 113 | /** |
||
| 114 | * Give the sort order for this view. |
||
| 115 | * |
||
| 116 | * @return int |
||
| 117 | */ |
||
| 118 | public function sortOrder() |
||
| 122 | } |
||
| 123 |
Let’s assume that you have a directory layout like this:
. |-- OtherDir | |-- Bar.php | `-- Foo.php `-- SomeDir `-- Foo.phpand let’s assume the following content of
Bar.php:If both files
OtherDir/Foo.phpandSomeDir/Foo.phpare 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.phpHowever, as
OtherDir/Foo.phpdoes 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: