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 |
||
19 | class PagePartTwigExtension extends AbstractExtension |
||
20 | { |
||
21 | /** |
||
22 | * @var EntityManager |
||
23 | */ |
||
24 | protected $em; |
||
25 | |||
26 | /** |
||
27 | * @param EntityManager $em |
||
28 | */ |
||
29 | public function __construct(EntityManager $em) |
||
33 | |||
34 | /** |
||
35 | * @return array |
||
36 | */ |
||
37 | public function getFunctions() |
||
45 | |||
46 | /** |
||
47 | * @param Environment $env |
||
48 | * @param array $twigContext The twig context |
||
49 | * @param HasPagePartsInterface $page The page |
||
50 | * @param string $contextName The pagepart context |
||
51 | * @param array $parameters Some extra parameters |
||
52 | * |
||
53 | * @return string |
||
54 | */ |
||
55 | View Code Duplication | public function renderPageParts(Environment $env, array $twigContext, HasPagePartsInterface $page, $contextName = 'main', array $parameters = array()) |
|
68 | |||
69 | /** |
||
70 | * @param HasPagePartsInterface $page The page |
||
71 | * @param string $context The pagepart context |
||
72 | * |
||
73 | * @return PagePartInterface[] |
||
74 | */ |
||
75 | public function getPageParts(HasPagePartsInterface $page, $context = 'main') |
||
82 | |||
83 | /** |
||
84 | * @param HasPagePartsInterface $page |
||
85 | * @param string $context |
||
86 | * |
||
87 | * @return bool |
||
88 | */ |
||
89 | public function hasPageParts(HasPagePartsInterface $page, $context = 'main') |
||
93 | } |
||
94 |
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.