title: How to correctly close an Entity Manager in doctrine
body: <p>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.</p>
  
  <p>Before I knew you could (and should) clear the Entity Manager, every 20 iterations i did the following:</p>
  
  <pre><code>if ($this-&gt;usersCalculated % 20 == 0) {
     $this-&gt;em-&gt;close();
     $this-&gt;em = \Bootstrap::createEm();
     $this-&gt;loadRepositories();
  }
  </code></pre>
  
  <p>And the Bootstrap::createEm looks like this:</p>
  
  <pre><code>public static function createEm() {
      $em = EntityManager::create(Bootstrap::$connectionOptions, Bootstrap::$config);
      $em-&gt;getConnection()-&gt;setCharset('utf8');
      return $em;
  }
  </code></pre>
  
  <p>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. </p>
  
  <p>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:</p>
  
  <pre><code>    $emailSent = new \model\EmailSent();
      $emailSent-&gt;setStuff();
      // I do it in a new em to not affect whatever currentunit was doing.
      $newEm = \Bootstrap::createEm();
      $newEm-&gt;persist($emailSent);
      $newEm-&gt;flush();
      $newEm-&gt;close();
  </code></pre>
  
  <p>From what I've learned from before, that leaves some memory leaked behind.</p>
  
  <p>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?</p>