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 |
||
14 | class URLHelper |
||
15 | { |
||
16 | use URLValidator; |
||
17 | |||
18 | /** |
||
19 | * @var EntityManager |
||
20 | */ |
||
21 | private $em; |
||
22 | |||
23 | /** |
||
24 | * @var RouterInterface |
||
25 | */ |
||
26 | private $router; |
||
27 | |||
28 | /** |
||
29 | * @var LoggerInterface |
||
30 | */ |
||
31 | private $logger; |
||
32 | |||
33 | /** |
||
34 | * @var array|null |
||
35 | */ |
||
36 | private $nodeTranslationMap; |
||
37 | |||
38 | /** |
||
39 | * @var array|null |
||
40 | */ |
||
41 | private $mediaMap; |
||
42 | |||
43 | /** |
||
44 | * @var DomainConfigurationInterface |
||
45 | */ |
||
46 | private $domainConfiguration; |
||
47 | |||
48 | /** |
||
49 | * @param EntityManager $em |
||
50 | * @param RouterInterface $router |
||
51 | * @param LoggerInterface $logger |
||
52 | * @param DomainConfigurationInterface $domainConfiguration |
||
53 | */ |
||
54 | public function __construct(EntityManager $em, RouterInterface $router, LoggerInterface $logger, DomainConfigurationInterface $domainConfiguration) |
||
61 | |||
62 | /** |
||
63 | * Replace a given text, according to the node translation id and the multidomain site id. |
||
64 | * |
||
65 | * @param $text |
||
66 | * |
||
67 | * @return mixed |
||
68 | */ |
||
69 | public function replaceUrl($text) |
||
144 | |||
145 | /** |
||
146 | * Get a map of all node translations. Only called once for caching. |
||
147 | * |
||
148 | * @return array|null |
||
149 | * |
||
150 | * @throws \Doctrine\DBAL\DBALException |
||
151 | */ |
||
152 | View Code Duplication | private function getNodeTranslationMap() |
|
163 | |||
164 | /** |
||
165 | * Get a map of all media items. Only called once for caching. |
||
166 | * |
||
167 | * @return array|null |
||
168 | * |
||
169 | * @throws \Doctrine\DBAL\DBALException |
||
170 | */ |
||
171 | View Code Duplication | private function getMediaMap() |
|
182 | } |
||
183 |
The
EntityManager
might 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
EntityManager
is closed. Any other code which depends on the same instance of theEntityManager
during 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.