From the point of view of the MVC and Symfony2 pattern, I can slightly reduce my controller code by discarding some save logic . For example, given a standard new action like this:
public function newAction(\Symfony\Component\HttpFoundation\Request $request) { // Create a new entity and a new form type for managing $entity = $this->createNewEntity(); $form = $this->createForm($this->createNewFormType(), $entity); // If it GET just return the view if('GET' == $request->getMethod()) return array('form' => $form->createView()); // It POST request so bind the form $form->bindRequest($request); // ... and if it valid just persist the entity if($form->isValid()) : $em = $this->getEntityManager(); // Should be carried by controller? $em->persist($entity); // Should be carried by controller? $em->flush(); // Should be carried by controller? // Redirect the user to the default page return $this->redirect($this->getOnNewSuccessRedirectUrl($entity)); endif; // Return the view plus errors return array( 'errors' => $this->getValidator()->validate($entity), 'form' => $form->createView() ); }
Would it be correct to move the logic to the repository ? Example (warning: may not work):
class BaseRepository extends \Doctrine\ORM\EntityRepository { public function save($entity) { $em = $this->_em; $em->persist($entity); $em->flush(); } public function delete($entity) { $em = $this->_em; $em->remove($entity); $em->flush(); } }
Controller Code:
if($form->isValid()) : $this->getRepository()->save($entity);
gremo
source share