【问题标题】:Symfony 3 controller entity argumentsSymfony 3 控制器实体参数
【发布时间】:2016-02-24 20:32:16
【问题描述】:

从 Symfony 2.7 升级到 3.0.2 后,我注意到 crud generator 的控制器发生了变化。

Symfony 2 示例:

/**
 * Finds and displays a Article entity.
 *
 * @Route("/{id}", name="article_show")
 * @Method("GET")
 * @Template("AppBundle:article:show.html.twig")
 */
public function showAction($id)
{
    $em = $this->getDoctrine()->getManager();

    $entity = $em->getRepository('AppBundle:Article')->find($id);

    if (!$entity) {
        throw $this->createNotFoundException('Unable to find Article entity.');
    }

    $deleteForm = $this->createDeleteForm($id);

    return array(
        'entity'      => $entity,
        'delete_form' => $deleteForm->createView(),
    );
}

Symfony 3 示例:

/**
 * Finds and displays a Article entity.
 *
 * @Route("/{id}", name="article_show")
 * @Method("GET")
 */
public function showAction(Article $article)
{
    $deleteForm = $this->createDeleteForm($article);

    return $this->render('article/show.html.twig', array(
        'article' => $article,
        'delete_form' => $deleteForm->createView(),
    ));
}

不确定这到底是什么时候改变的,因为我在使用 2.8 版时没有使用 crud 生成器。

不管怎样,我感兴趣的魔法是这样的:

public function showAction(Article $article)

这似乎与早期版本相同:

    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();
        $entity = $em->getRepository('AppBundle:Article')->find($id);
        ...
    }

我在 Symfony 网站上找不到任何关于此的文档。有人可以解释一下这个功能是如何工作的,我在哪里可以找到更多信息?它仅适用于实体,还是...?

谢谢!

【问题讨论】:

    标签: crud symfony


    【解决方案1】:

    此功能称为 ParamConverter - 在此处阅读更多信息:http://symfony.com/doc/current/bundles/SensioFrameworkExtraBundle/annotations/converters.html

    在您的控制器中,您没有 @ParamConverter 注释,因为:

    If you use type hinting as in the example above, you can even omit the @ParamConverter annotation altogether

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-06
      • 1970-01-01
      • 1970-01-01
      • 2018-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-31
      相关资源
      最近更新 更多