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 |
||
| 10 | abstract class AbstractMapper |
||
| 11 | { |
||
| 12 | abstract protected function getEntityRepository(); |
||
| 13 | |||
| 14 | /** |
||
| 15 | * @var \Doctrine\ORM\EntityManager |
||
| 16 | */ |
||
| 17 | protected $em; |
||
| 18 | |||
| 19 | /** |
||
| 20 | * @var \Doctrine\ORM\EntityRepository |
||
| 21 | */ |
||
| 22 | protected $er; |
||
| 23 | |||
| 24 | /** |
||
| 25 | * @var ServiceLocatorInterface |
||
| 26 | */ |
||
| 27 | protected $serviceLocator; |
||
| 28 | |||
| 29 | /** |
||
| 30 | * @var \PlaygroundGame\Options\ModuleOptions |
||
| 31 | */ |
||
| 32 | protected $options; |
||
| 33 | |||
| 34 | public function __construct(EntityManager $em, ModuleOptions $options, ServiceLocatorInterface $locator) |
||
| 40 | |||
| 41 | public function findById($id) |
||
| 45 | |||
| 46 | public function findBy($filter, $order = null, $limit = null, $offset = null) |
||
| 50 | |||
| 51 | public function findOneBy($array = array(), $sortBy = array()) |
||
| 57 | |||
| 58 | public function findAll() |
||
| 62 | |||
| 63 | public function update($entity) |
||
| 67 | |||
| 68 | View Code Duplication | public function insert($entity) |
|
| 80 | |||
| 81 | View Code Duplication | protected function persist($entity) |
|
| 94 | |||
| 95 | public function remove($entity) |
||
| 100 | |||
| 101 | public function removeAll($entities) |
||
| 108 | } |
||
| 109 |
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.