Home » Php » php – How to correctly close an Entity Manager in doctrine

php – How to correctly close an Entity Manager in doctrine

Posted by: admin July 12, 2020 Leave a comment


I was having a memory leak problem in a Doctrine2 script that was aparently caused by a piece of code that was supposed to eliminate memory problems.

Before I knew you could (and should) clear the Entity Manager, every 20 iterations i did the following:

if ($this->usersCalculated % 20 == 0) {
   $this->em = \Bootstrap::createEm();

And the Bootstrap::createEm looks like this:

public static function createEm() {
    $em = EntityManager::create(Bootstrap::$connectionOptions, Bootstrap::$config);
    return $em;

The reason that I recreated the Entity Manager in the first place was because my UnitOfWork was growing wild and I didn’t know about the $em->clear() method.

So, even if my current memory leak seems solved at the moment (or at least reduced), i still have to create a new Entity Manager whenever I need to do a separate insert/update query without relying that someone else do the flush. For example, whenever I send an email, I insert a row in the database to indicate so, and the code looks like this:

    $emailSent = new \model\EmailSent();
    // I do it in a new em to not affect whatever currentunit was doing.
    $newEm = \Bootstrap::createEm();

From what I’ve learned from before, that leaves some memory leaked behind.

So my question is, what am I doing wrong here? why is this leaking memory and how should I really close/recreate an entity manager?

How to&Answers:

Have you tried:


I’ve read that this turns off the SQL Logger which is not cleared and sometimes produces memory leaks like you are experiencing.


Have you tried actually using the clear method instead of close?

I hope this helps you—> Batch Processing