You have injected the EntityManager via parameter $entityManager. This is generally not recommended as it might get closed and become unusable. Instead, it is recommended to inject the ManagerRegistry and retrieve the EntityManager via getManager() each time you need it.
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:
functionsomeFunction(ManagerRegistry$registry){$em=$registry->getManager();$em->getConnection()->beginTransaction();try{// Do something.$em->getConnection()->commit();}catch(\Exception$ex){$em->getConnection()->rollback();$em->close();throw$ex;}}
If that code throws an exception and the EntityManager is closed. Any other
code which depends on the same instance of the EntityManager during this
request will fail.
On the other hand, if you instead inject the ManagerRegistry, the getManager()
method guarantees that you will always get a usable manager instance.
Loading history...
17
{
18
$this->entityManager = $entityManager;
19
}
20
21
public function transform($value)
22
{
23
if (null === $value) {
24
return null;
25
}
26
27
if (!$value instanceof Invitation) {
28
throw new UnexpectedTypeException($value, 'AppBundle\Entity\Invitation');
29
}
30
31
return $value->getCode();
32
}
33
34
public function reverseTransform($value)
35
{
36
if (null === $value || '' === $value) {
37
return null;
38
}
39
40
if (!is_string($value)) {
41
throw new UnexpectedTypeException($value, 'string');
42
}
43
44
$dql = <<<DQL
45
SELECT i
46
FROM AppBundle:Invitation i
47
WHERE i.code = :code
48
AND NOT EXISTS(SELECT 1 FROM AppBundle:User u WHERE u.invitation = i)
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.