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 |
||
| 18 | class FileHelper |
||
| 19 | { |
||
| 20 | /** |
||
| 21 | * @var EntityManager |
||
| 22 | */ |
||
| 23 | protected $manager; |
||
| 24 | |||
| 25 | /** |
||
| 26 | * FileHelper constructor. |
||
| 27 | * @param EntityManager $manager |
||
| 28 | */ |
||
| 29 | public function __construct(EntityManager $manager) |
||
| 33 | |||
| 34 | /** |
||
| 35 | * @param string $path |
||
| 36 | * @param string $name |
||
| 37 | * @param integer $size |
||
| 38 | */ |
||
| 39 | View Code Duplication | public function tryToStoreMovie($path, $name, $size) |
|
| 49 | |||
| 50 | /** |
||
| 51 | * @param string $path |
||
| 52 | * @param string $name |
||
| 53 | * @param integer $size |
||
| 54 | */ |
||
| 55 | View Code Duplication | public function tryToStoreGame($path, $name, $size) |
|
| 65 | |||
| 66 | /** |
||
| 67 | * @param string $path |
||
| 68 | * @param string $name |
||
| 69 | * @param integer $size |
||
| 70 | */ |
||
| 71 | View Code Duplication | public function tryToStoreSoftware($path, $name, $size) |
|
| 81 | |||
| 82 | /** |
||
| 83 | * @param string $path |
||
| 84 | * @param string $name |
||
| 85 | * @param integer $size |
||
| 86 | */ |
||
| 87 | View Code Duplication | public function tryToStoreOther($path, $name, $size) |
|
| 97 | |||
| 98 | /** |
||
| 99 | * @param Serie[] $series |
||
| 100 | * @param string[] $pathsDone |
||
| 101 | * @param string $ext |
||
| 102 | * @param string $path |
||
| 103 | * @param string $name |
||
| 104 | * @param integer $size |
||
| 105 | */ |
||
| 106 | public function tryToStoreSerie(&$series, &$pathsDone, $ext, $path, $name, $size) |
||
| 148 | |||
| 149 | /** |
||
| 150 | * @param \KI\PonthubBundle\Entity\PonthubFile $item |
||
| 151 | * @param integer $size |
||
| 152 | * @param string $path |
||
| 153 | * @param string $name |
||
| 154 | * @return \KI\PonthubBundle\Entity\PonthubFile |
||
| 155 | */ |
||
| 156 | private function basicInfos($item, $size, $path, $name) |
||
| 165 | } |
||
| 166 |
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.