【发布时间】:2016-07-26 08:40:54
【问题描述】:
我正在尝试了解 Symfoy CRUD 控制器的工作原理,我在 Google 上搜索了很多,但找不到任何答案。
所以问题是,控制器如何知道哪个实体被传递给路由? 例如:
在这个索引路由中,我们调用了学说管理器,然后从数据库中拉出所有的 cmets。
/**
* Lists all Comment entities.
*
* @Route("/", name="admin_comment_index")
* @Method("GET")
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$comments = $em->getRepository('AppBundle:Comment')->findAll();
return $this->render('comment/index.html.twig', array(
'comments' => $comments,
));
}
但在下一个“新”操作中,我们不会调用任何学说实例。控制器似乎已经知道哪个实体正在运行。
/**
* Creates a new Comment entity.
*
* @Route("/new", name="admin_comment_new")
* @Method({"GET", "POST"})
*/
public function newAction(Request $request)
{
$comment = new Comment();
$form = $this->createForm('AppBundle\Form\CommentType', $comment);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($comment);
$em->flush();
return $this->redirectToRoute('admin_comment_show', array('id' => $comment->getId()));
}
return $this->render('comment/new.html.twig', array(
'comment' => $comment,
'form' => $form->createView(),
));
}
我猜这是因为第二条路由获得了“请求”对象,实体是否存储在其中?我想有更深入的解释。
更新:“新”动作现在对我来说似乎很清楚,这是我试图弄清楚的一个坏例子,但让我们看看“编辑”动作:
public function editAction(Request $request, Comment $comment)
{
$deleteForm = $this->createDeleteForm($comment);
$editForm = $this->createForm('AppBundle\Form\CommentType', $comment);
$editForm->handleRequest($request);
if ($editForm->isSubmitted() && $editForm->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($comment);
$em->flush();
return $this->redirectToRoute('admin_comment_edit', array('id' => $comment->getId()));
}
return $this->render('comment/edit.html.twig', array(
'comment' => $comment,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
));
}
这一次,表单已经渲染了其中的数据,但我们只是在请求中传递了“id”
<a href="{{ path('admin_comment_edit', { 'id': comment.id }) }}">edit</a>
这次的数据来自哪里?似乎来自评论对象,它被传递到控制器中,但我看不出它来自哪里。 对不起我的问题和糟糕的英语!
【问题讨论】:
-
如果是“new”,需要从数据库中获取什么对象?
-
@Eiko 是的,这是一个不好的例子,那么“编辑”功能呢?请看我帖子中的更新!
-
in
editActionSymfony 加载由于 type-hinting 而传递的 id 中的实体 -
@Jeet 非常感谢,正是我需要的信息。
-
很高兴,它帮助了你。 :)
标签: php symfony doctrine-orm crud