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 CloneHelper |
||
15 | { |
||
16 | /** |
||
17 | * @var EntityManager |
||
18 | */ |
||
19 | private $em; |
||
20 | |||
21 | /** |
||
22 | * @var EventDispatcherInterface |
||
23 | */ |
||
24 | private $eventDispatcher; |
||
25 | |||
26 | /** |
||
27 | * @param EntityManager $em The EntityManager |
||
28 | * @param EventDispatcherInterface $eventDispatcher The EventDispatchInterface |
||
29 | */ |
||
30 | public function __construct(EntityManager $em, EventDispatcherInterface $eventDispatcher) |
||
35 | |||
36 | /** |
||
37 | * @param mixed $entity |
||
38 | * |
||
39 | * @return mixed |
||
40 | */ |
||
41 | public function deepCloneAndSave($entity) |
||
53 | |||
54 | /** |
||
55 | * @param object $event |
||
56 | * @param string $eventName |
||
57 | * |
||
58 | * @return object |
||
59 | */ |
||
60 | View Code Duplication | private function dispatch($event, string $eventName) |
|
70 | } |
||
71 |
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.