Từ quan điểm của mẫu MVC và Symfony2, tôi có thể giảm bớt mã điều khiển chỉ một chút, di chuyển một số logic tiếp tục? Ví dụ, cho một hành động mới tiêu chuẩn như thế này:Giảm bớt bộ điều khiển Symfony2 và tiếp tục logic
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's GET just return the view
if('GET' == $request->getMethod())
return array('form' => $form->createView());
// It's POST request so bind the form
$form->bindRequest($request);
// ... and if it's 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()
);
}
Sẽ là đúng di chuyển mà logic để kho? Một ví dụ (cảnh báo: có thể không hoạt động):
class BaseRepository extends \Doctrine\ORM\EntityRepository
{
/**
* Persist the entity (either new or existent)
*
* @param object $entity
*/
public function save($entity)
{
$em = $this->_em;
$em->persist($entity);
$em->flush();
}
/**
* Delete the entity.
*
* @param object $entity
*/
public function delete($entity)
{
$em = $this->_em;
$em->remove($entity);
$em->flush();
}
}
Mã điều khiển sẽ là:
if($form->isValid()) :
$this->getRepository()->save($entity);
// Redirect the user to the default page
return $this->redirect($this->getOnNewSuccessRedirectUrl($entity));
endif;
Bằng cách gọi $ em-> flush ($ entity); thay vì $ em-> flush(); bạn chỉ đang thực hiện các thay đổi cho thực thể đã cho và liên quan các thực thể con. –