根据路由参数将 Doctrine Entity 注入 Symfony 控制器

Injecting Doctrine Entity into Symfony controller based on route parameters

我想根据路由参数将 Doctrine 实体注入到控制器操作中,以尝试减少我的控制器中疯狂的代码重复量。

例如我有以下路线

product:
    path:     /product/edit/{productId}
    defaults: { _controller: ExampleBundle:Product:edit }

而不是我目前的方法

public function editAction($productId)
{
    $manager = $this->getDoctrine()->getManager();
    $product = $manager->getRepository('ExampleBundle:Product')
        ->findOneByProductId($productId);

    if (!$product) {
        $this->addFlash('error', 'Selected product does not exist');
        return $this->redirect($this->generateUrl('products'));
    }

    // ...
}

我希望在其他地方处理这个问题,因为它目前在至少 6 个控制器操作中重复出现。所以它会更符合

public function editAction(Product $product)
{
    // ...
}

似乎这实际上已经完成了,我能找到的最好的例子是由 SensioFrameworkBundle http://symfony.com/doc/current/bundles/SensioFrameworkExtraBundle/annotations/converters.html

我会使用它,但没有在我们的 Symfony 项目中使用注释,因此需要寻找替代方案。关于如何实现这一点有什么建议吗?

如果您仔细阅读 the docs,您将了解到参数转换器实际上可以在没有注释的情况下工作:

To detect which converter is run on a parameter the following process is run:

  • If an explicit converter choice was made with @ParamConverter(converter="name") the converter with the given name is chosen.
  • Otherwise all registered parameter converters are iterated by priority. The supports() method is invoked to check if a param converter can convert the request into the required parameter. If it returns true the param converter is invoked.

换句话说,如果您没有在注释中指定参数转换器,Symfony 将遍历所有已注册的转换器并找到最合适的转换器来处理您的参数(基于类型提示)。

我更喜欢添加注释以便:

  • 明确
  • 节省一些处理时间