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 |
||
| 15 | class UserFactory |
||
| 16 | { |
||
| 17 | /** |
||
| 18 | * @var EntityManager |
||
| 19 | */ |
||
| 20 | private $em; |
||
| 21 | |||
| 22 | /** |
||
| 23 | * @var EntityRepository |
||
| 24 | */ |
||
| 25 | private $userRepository; |
||
| 26 | |||
| 27 | /** |
||
| 28 | * @param EntityManager $em |
||
| 29 | */ |
||
| 30 | public function __construct(EntityManager $em) |
||
| 35 | |||
| 36 | /** |
||
| 37 | * @param array $data |
||
| 38 | * |
||
| 39 | * @return User |
||
| 40 | * @throws ApiException |
||
| 41 | * @throws InvalidResponseException |
||
| 42 | */ |
||
| 43 | public function createFromArray(array $data) |
||
| 62 | |||
| 63 | /** |
||
| 64 | * @param UserDTO $userData |
||
| 65 | * |
||
| 66 | * @return User |
||
| 67 | * @throws ApiException |
||
| 68 | * @throws InvalidUserDataException |
||
| 69 | */ |
||
| 70 | public function createFromDTO(UserDTO $userData) |
||
| 89 | |||
| 90 | /** |
||
| 91 | * @param array $data |
||
| 92 | * |
||
| 93 | * @throws InvalidResponseException |
||
| 94 | */ |
||
| 95 | private function validateArrayData(array $data) |
||
| 101 | |||
| 102 | /** |
||
| 103 | * @param array $data |
||
| 104 | * |
||
| 105 | * @throws InvalidResponseException |
||
| 106 | */ |
||
| 107 | private function validateDTOData(UserDTO $data) |
||
| 113 | } |
The
EntityManagermight become unusable for example if a transaction is rolled back and it gets closed. Let’s assume that somewhere in your application, or in a third-party library, there is code such as the following:If that code throws an exception and the
EntityManageris closed. Any other code which depends on the same instance of theEntityManagerduring this request will fail.On the other hand, if you instead inject the
ManagerRegistry, thegetManager()method guarantees that you will always get a usable manager instance.