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 |
||
| 24 | class Container extends Forms\Container |
||
| 25 | { |
||
| 26 | /** |
||
| 27 | * Implement entity handling in form |
||
| 28 | */ |
||
| 29 | use TEntityContainer; |
||
| 30 | |||
| 31 | /** |
||
| 32 | * @var ORM\EntityManager |
||
| 33 | */ |
||
| 34 | private $entityManager; |
||
| 35 | |||
| 36 | /** |
||
| 37 | * @param ORM\EntityManager $entityManager |
||
| 38 | */ |
||
| 39 | public function __construct(ORM\EntityManager $entityManager) |
||
| 45 | |||
| 46 | /** |
||
| 47 | * Adds naming container to the form |
||
| 48 | * |
||
| 49 | * @param string $name |
||
| 50 | * |
||
| 51 | * @return Container |
||
| 52 | */ |
||
| 53 | View Code Duplication | public function addContainer($name) : Container |
|
| 60 | } |
||
| 61 |
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.