I had a memory leak problem in a Doctrine2 script that was explicitly caused by a piece of code that was supposed to fix memory problems.
Before I found out that you could (and should) clean up Entity Manager, I did the following every 20 iterations:
if ($this->usersCalculated % 20 == 0) { $this->em->close(); $this->em = \Bootstrap::createEm(); $this->loadRepositories(); }
And Bootstrap :: createEm looks like this:
public static function createEm() { $em = EntityManager::create(Bootstrap::$connectionOptions, Bootstrap::$config); $em->getConnection()->setCharset('utf8'); return $em; }
The reason I recreated Entity Manager was primarily due to the fact that my UnitOfWork was growing, and I did not know about the $ em-> clear () method.
So, even if my current memory leak seems to be resolved at the moment (or at least reduced), I still need to create a new Entity Manager when I need to make a separate insert / update request, without relying on who rinse something else. For example, whenever I send an email, I insert a row into the database to indicate this, and the code looks like this:
$emailSent = new \model\EmailSent(); $emailSent->setStuff(); // I do it in a new em to not affect whatever currentunit was doing. $newEm = \Bootstrap::createEm(); $newEm->persist($emailSent); $newEm->flush(); $newEm->close();
From what I learned earlier, this leaves a missing memory.
So my question is: what am I doing wrong here? why is it a memory leak and how should i really close / recreate the entity manager?
Hernan rajchert
source share