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 |
||
| 25 | class EntityForm extends Application\UI\Form |
||
| 26 | { |
||
| 27 | /** |
||
| 28 | * Implement entity handling in form |
||
| 29 | */ |
||
| 30 | use TEntityContainer; |
||
| 31 | |||
| 32 | /** |
||
| 33 | * Implement form methods |
||
| 34 | */ |
||
| 35 | use TForm; |
||
| 36 | |||
| 37 | /** |
||
| 38 | * @var ORM\EntityManager |
||
| 39 | */ |
||
| 40 | private $entityManager; |
||
| 41 | |||
| 42 | /** |
||
| 43 | * @param ORM\EntityManager $entityManager |
||
| 44 | * @param ComponentModel\IContainer|NULL $parent |
||
| 45 | * @param string|NULL $name |
||
| 46 | */ |
||
| 47 | public function __construct( |
||
| 56 | |||
| 57 | /** |
||
| 58 | * Adds naming container to the form |
||
| 59 | * |
||
| 60 | * @param string $name |
||
| 61 | * |
||
| 62 | * @return Container |
||
| 63 | */ |
||
| 64 | View Code Duplication | public function addContainer($name) : Container |
|
| 71 | } |
||
| 72 |
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.