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 |
||
| 21 | class Manager implements LoggerAwareInterface |
||
| 22 | { |
||
| 23 | use LoggerAwareTrait; |
||
| 24 | |||
| 25 | /** |
||
| 26 | * Constructor options: |
||
| 27 | * - `logger` |
||
| 28 | * |
||
| 29 | * @param array $data Constructor options. |
||
| 30 | */ |
||
| 31 | public function __construct(array $data) |
||
| 35 | |||
| 36 | /** |
||
| 37 | * @param Acl $acl The Zend Acl instant to load permissions to. |
||
| 38 | * @param array $permissions The array of permissions, in [role=>details] array. |
||
| 39 | * @param string $resource The Acl resource (string identifier) to load roles and permissions into. |
||
| 40 | * @return void |
||
| 41 | */ |
||
| 42 | public function loadPermissions(Acl &$acl, array $permissions, $resource = '') |
||
| 48 | |||
| 49 | /** |
||
| 50 | * @param Acl $acl The Zend Acl instance to load permissions to. |
||
| 51 | * @param PDO $db The PDO database instance. |
||
| 52 | * @param string $table The table where to fetch the roles and permissions. |
||
| 53 | * @param string $resource The Acl resource (string identifier) to load roles and permissions into. |
||
| 54 | * @return void |
||
| 55 | */ |
||
| 56 | public function loadDatabasePermissions(Acl &$acl, PDO $db, $table, $resource = '') |
||
| 85 | |||
| 86 | /** |
||
| 87 | * @param Acl $acl The Zend Acl instant to add permissions to. |
||
| 88 | * @param string $role The role (string identifier) to add. |
||
| 89 | * @param array $permissions The permissions details (array) to add. |
||
| 90 | * @param string $resource The Acl resource (string identifier) to add roles and permissions into. |
||
| 91 | * @return void |
||
| 92 | */ |
||
| 93 | private function addRoleAndPermissions(Acl &$acl, $role, array $permissions, $resource) |
||
| 129 | } |
||
| 130 |
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: