title: Slimming down Symfony2 controller and persist logic
body: <p>From the point of view of MVC pattern and Symfony2, can i slim down my <strong>controller code</strong> just a bit, moving away some <strong>persist logic</strong>? For example, given a standard new action like this:</p>
  
  <pre><code>public function newAction(\Symfony\Component\HttpFoundation\Request $request)
  {
  
      // Create a new entity and a new form type for managing
      $entity = $this-&gt;createNewEntity();
      $form   = $this-&gt;createForm($this-&gt;createNewFormType(), $entity);
  
      // If it's GET just return the view
      if('GET' == $request-&gt;getMethod())
          return array('form' =&gt; $form-&gt;createView());
  
      // It's POST request so bind the form
      $form-&gt;bindRequest($request);
  
      // ... and if it's valid just persist the entity
      if($form-&gt;isValid()) :
  
          $em = $this-&gt;getEntityManager(); // Should be carried by controller?
          $em-&gt;persist($entity);           // Should be carried by controller?
          $em-&gt;flush();                    // Should be carried by controller?
  
          // Redirect the user to the default page
          return $this-&gt;redirect($this-&gt;getOnNewSuccessRedirectUrl($entity));
  
      endif;
  
      // Return the view plus errors
      return array(
          'errors' =&gt; $this-&gt;getValidator()-&gt;validate($entity),
          'form'   =&gt; $form-&gt;createView()
      );
  
  }
  </code></pre>
  
  <p>Would be correct moving that <strong>logic to the repository</strong>? An example (warning: may not work):</p>
  
  <pre><code>class BaseRepository extends \Doctrine\ORM\EntityRepository
  {
  
      /**
       * Persist the entity (either new or existent)
       *
       * @param object $entity
       */
      public function save($entity)
      {
          $em = $this-&gt;_em;
          $em-&gt;persist($entity);
          $em-&gt;flush();
      }
  
      /**
       * Delete the entity.
       *
       * @param object $entity
       */
      public function delete($entity)
      {
          $em = $this-&gt;_em;
          $em-&gt;remove($entity);
          $em-&gt;flush();
      }
  
  }
  </code></pre>
  
  <p>The controller code would be:</p>
  
  <pre><code>if($form-&gt;isValid()) :
  
      $this-&gt;getRepository()-&gt;save($entity);
  
      // Redirect the user to the default page
      return $this-&gt;redirect($this-&gt;getOnNewSuccessRedirectUrl($entity));
  
  endif;
  </code></pre>